一、导入jar包
png代码
c3p0dUtils.java
package work.zhangdoudou.Utils;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class c3p0dUtils {
private static final String DRIVER_CLASS="com.mysql.jdbc.Driver";
private static final String URL="jdbc:mysql://localhost:3306/bbs";
private static final String USER="root";
private static final String PASSWORD="root";
private static ComboPooledDataSource DATA_SOURCE;
static{
DATA_SOURCE=new ComboPooledDataSource();
try {
DATA_SOURCE.setDriverClass(DRIVER_CLASS);
DATA_SOURCE.setJdbcUrl(URL);
DATA_SOURCE.setUser(USER);
DATA_SOURCE.setPassword(PASSWORD);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
//提供获得数据源
public static ComboPooledDataSource getDataSource(){
return DATA_SOURCE;
}
//提供获得链接
public static Connection getConnection() throws SQLException {
return DATA_SOURCE.getConnection();
}
}
测试类TestC3p0Utils.java
package work.zhangdoudou.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import work.zhangdoudou.Utils.c3p0dUtils;
public class TestC3p0Utils {
@Test
public void test() throws SQLException{
Connection connection=c3p0dUtils.getConnection();
String sql="select u_name from users";
Statement statement=connection.createStatement();
ResultSet resultSet=statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getString("u_name"));
}
connection.close;
}
}
网友评论