使用C3p0操做數據庫

package dbUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.utils.C3p0Utils;

public class DbUtlisTest {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     

//新增

public static void test1 () throws SQLException{
QueryRunner run = new QueryRunner(C3p0Utils.getDatatSource());
run.update("insert into stu(id,name,sex) values(?,?,?)","10001","jack","1");
}

//事物   開啓事物必須傳遞Connection
public static void test2() throws SQLException{
Connection con = C3p0Utils.getConnection();
try {
con.setAutoCommit(false);
QueryRunner run = new QueryRunner();
run.update(con,"insert into stu(id,name,sex) values(?,?,?)",new Object[]{10004,"mary","0"});
run.update(con,"insert into stu(id,name,sex) values(?,?,?)",10005,"mark","1");
con.commit();
System.err.println("jieshu");
}catch (Exception e) {
System.err.println(e.getMessage());
con.rollback();
} finally {
con.close();
}
}
//查詢封裝
public static void test4()throws SQLException{
     Connection con = C3p0Utils.getConnection();
     QueryRunner run = new QueryRunner();
     List<Stu> list = run.query(con, "select * from stu",new BeanListHandler<>(Stu.class));
     for (int i = 0; i < list.size(); i++) {
         Stu stu = list.get(i);
         System.err.println(stu.toString());
     }
}
//修改  
public static void test5()throws SQLException{
    QueryRunner run = new QueryRunner(C3p0Utils.getDatatSource());
    int n = run.update("update stu set name =? where id = ?","jack333",1009);
    System.err.println(n);
}
//刪除
public static void test6()throws SQLException{
// QueryRunner run = new QueryRunner();
// int n = run.update(C3p0Utils.getConnection(),"delete from stu where id =?", 10003);
// 或者下面的
   QueryRunner run = new QueryRunner(C3p0Utils.getDatatSource());
   int n = run.update(C3p0Utils.getConnection(),"delete from stu where id =?", 10002);
   System.err.println(n);//0失敗   1成功
}
public static void main(String[] args) throws SQLException {
   test5();
}
}
相關文章
相關標籤/搜索