JAVA-使用連線池的DBUtils工具類及其使用
需要引入四個jar包
/********************************************/
package com.dxm.dbcp;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class JDBCUtils {
private static BasicDataSource dataSource = new BasicDataSource();
public static DataSource getDataSource() {
return dataSource;
}
static{
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mybase");
dataSource.setUsername("root");
dataSource.setPassword("1234");
dataSource.setInitialSize(10);//初始化連線數
dataSource.setMaxActive(8);//最大連線數量
dataSource.setMaxIdle(5);//最大空閒
dataSource.setMinIdle(1);//最小空閒
}
}
/*********************************/
package com.dxm.dbcp;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class QueryRunnerDemo {
private static QueryRunner qRunner=new QueryRunner(JDBCUtils.getDataSource());
public static void insert(){
String sql = "insert into sort(sname,sprice,sdesc) values(?,?,?)";
Object[] params= {"水果",100,"剛剛上市的核桃"};
try {
int row = qRunner.update(sql,params);
System.out.println(row);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("資料新增失敗");
}
}
public static void select(){
String sql="select * from sort";
try {
List<Object[]> query = qRunner.query(sql, new ArrayListHandler());
for (Object[] objects : query) {
for (Object object : objects) {
System.out.print(object+"\t");
}
System.out.println();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("查詢資料失敗!");
}
}
public static void main(String[] args) {
//insert();
select();
}
}