JdbcUtil的改进(c3p0的使用)
public class JdbcUtil {
//一个数据库只需要一个连接池对象,所以使用static
private static DataSource ds = new ComboPooledDataSource();
/**
* 获取连接池对象方法
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 获取连接对象
*/
public static Connection getConnection(){
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//关闭顺序为ResultSet Statement Connection
public static void close(Connection conn,Statement st){
try {
if (st!=null)
st.close();
if (conn!=null)
conn.close();//如今的close是把连接对象放回连接池中
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void close(Connection conn,Statement st,ResultSet rs){
try {
if (rs!=null)
rs.close();
close(conn,st);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1. 导包
2. update()的使用
public static void main(String[] args) {
QueryRunner qr = new QueryRunner(JdbcUtil.getDataSource());
try {
qr.update("insert into employee values(?,?,?,?,?,?)", new Object[]{null,"dd",22,"贵州","13123225786","男"});
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3. query()的使用
public class Demo2 {
public static void main(String[] args) {
QueryRunner qr = new QueryRunner(JdbcUtil.getDataSource());
/**
* ResultSetHandler接口: 用于把结果集封装成不同类型的对象
* ArrayHandler类: 把结果集的第一行结果封装成对象数组
* ArrayListHandler类: 把结果集的每一行结果封装成对象数组,把每个对象数组放入List集合中
* BeanHandler类: 把结果集的第一行,封装成javabean对象(常用)
* BeanListHandler类: 把结果集的每行封装成javabean,把每个javabean放入List集合中(常用)
* ScalarHandler类:查询聚合函数(例如:count(*)) (常用)
*/
//t1(qr);
//t2(qr);
//t3(qr);
//t4(qr);
try {
long count = (Long)qr.query("select count(*) from student", new ScalarHandler(), new Object[]{});
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void t4(QueryRunner qr) {
try {
List<Student> stu= (List<Student>)qr.query("select * from student", new BeanListHandler(Student.class), new Object[]{});
for (Student student : stu) {
System.out.println(student);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void t3(QueryRunner qr) {
try {
Student stu= (Student)qr.query("select * from student where id=?", new BeanHandler(Student.class), new Object[]{1});//获取第一个bean对象
System.out.println(stu);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void t2(QueryRunner qr) {
try {
List<Object[]> values = (List<Object[]>)qr.query("select * from student", new ArrayListHandler(), new Object[]{});
for (Object[] arr : values) {//行
for (Object object : arr) {
System.out.print(object+"\t");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void t1(QueryRunner qr) {
try {
Object[] values = (Object[])qr.query("select * from student", new ArrayHandler(), new Object[]{});
for (Object object : values) {
System.out.println(object);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}