连接数据库
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* JDBC操作的工具类
* Created by yangrb on 17-6-21.
*/
public class JdbcUtils {
/**
* 释放connection
* @param connection
*/
public static void releaseConnection(Connection connection){
try {
if (connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static DataSource dataSource = null;
/**
* 数据源只能创建一次.故不能多次创建
*/
static{
dataSource = new ComboPooledDataSource("mvcapp");
}
/**
* 返回数据源的一个Connection对象
* @return
*/
public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
}
}
利用QueryRunner进行操作
private QueryRunner queryRunner = new QueryRunner();
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
return (E) queryRunner.query(connection,sql,new ScalarHandler(),args);
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils.releaseConnection(connection);
}