Java连载142-使用数据库连接池批量查询数据

一、创建一个数据库连接池

  • 首先建立工程chaper03,然后在src目录下创建xml文件
  • 该文件中定义了数据的密码的属性,用于连接数据库
<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>
    <named-config name="qfedu">
        <propertyname="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl" >jdbc:mysql:192.168.1.9:3306?encodingCharacter=utf8&amp;//</property>
        <property name="user">root</property>
        <property name="password">nicaibudao</property>
        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">20</property>
        <property name="minPoolSize">10</property>
        <property name="maxPoolSize">40</property>
        <property name="maxStatement">0</property>
        <property name="maxStatementPerConnection">5</property>
    </named-config>
    
</c3p0-config>
  • 然后创建一个com.qfedu.utils的包,创建一个工具类C3P0Utils,用于连接数据库等操作
package com.qfedu.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {
	private static ComboPooledDataSource dataSource = new ComboPooledDataSource("qfedu");
	
	public static DataSource getDataSource() {
		return dataSource;
	}

}
  • 书写查询语句
package com.qfedu.test;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import com.qfedu.utils.C3P0Utils;

public class TestDBUtils_ColumnListHandler {
	public static void main(String[] args) throws SQLException{
		QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
		
		String sql = "select * from students";
		List<Object> list = (List<Object>) queryRunner.query(sql, new ColumnListHandler("s_name"));
		
		System.out.println(list);
	}
}

二、源码:

上一篇:canvas绘制圣诞树


下一篇:Android自定义view流程