标签:etc 3.2 连接池 localhost tst connect 文件 abc 遍历
@Test
public void demo1() throws Exception{
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获得连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web_test3", "root", "abc");
//执行SQL
// 3.1获得执行SQL语句的对象
Statement statement = conn.createStatement();
// 3.2编写SQL语句:
String sql = "select * from user";
// 3.3执行SQL:
ResultSet rs = statement.executeQuery(sql);
// 3.4遍历结果集:
while(rs.next()){
System.out.print(rs.getInt("id")+" ");
System.out.print(rs.getString("username")+" ");
System.out.print(rs.getString("password")+" ");
System.out.print(rs.getString("nickname")+" ");
System.out.print(rs.getInt("age"));
System.out.println();
}
// 4.释放资源
rs.close();
statement.close();
conn.close();
@Test /** * 手动设置参数的方式: */ public void demo1(){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try{ // 获得连接:从连接池中获取: // 创建连接池: ComboPooledDataSource dataSource = new ComboPooledDataSource(); // 设置连接参数: dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql:///web_test4"); dataSource.setUser("root"); dataSource.setPassword("abc"); // 从连接池中获得连接: conn = dataSource.getConnection(); // 编写SQL: String sql = "select * from account"; // 预编译SQL: pstmt = conn.prepareStatement(sql); // 执行SQL: rs = pstmt.executeQuery(); while(rs.next()){ System.out.println(rs.getInt("id")+" "+rs.getString("name")+" "+rs.getDouble("money")); } }catch(Exception e){ e.printStackTrace(); }finally{ JDBCUtils.release(rs, pstmt, conn); } }
标签:etc 3.2 连接池 localhost tst connect 文件 abc 遍历
原文地址:https://www.cnblogs.com/govzhou/p/9523461.html