当前位置:Gxlcms > 数据库问题 > Java之JDBC操作

Java之JDBC操作

时间:2021-07-01 10:21:17 帮助过:3人阅读

/** 2 * 使用JDBC底层实现查询 3 */ 4 public static void queryWithJDBC() { 5 Connection conn = null; 6 PreparedStatement psmt = null; 7 ResultSet rs = null; 8 String jdbcUrl = "jdbc:mysql://192.168.184.130:3306/gxrdb"; 9 10 try { 11 // 加载驱动 12 Class.forName("com.mysql.jdbc.Driver"); 13 // 创建连接 14 conn = DriverManager.getConnection(jdbcUrl, "root", "root"); 15 String sql = "select * from user where name = ?"; 16 // 预编译sql 17 psmt = conn.prepareStatement(sql); 18 // 从1开始,没有就不需要 19 psmt.setString(1, "Tom"); 20 // 执行sql 21 rs = psmt.executeQuery(); 22 // int num = psmt.executeUpdate(); //增删改,返回操作记录数 23 24 // 遍历结果集 25 while (rs.next()) { 26 //根据列名查询对应的值,也可以是位置序号 27 String name = rs.getString("name"); 28 String age = rs.getString("age"); 29 System.out.println(name); 30 System.out.println(age); 31 } 32 } catch (Exception e) { 33 e.printStackTrace(); 34 } finally { 35 try { 36 rs.close(); 37 psmt.close(); 38 conn.close(); 39 } catch (SQLException e) { 40 e.printStackTrace(); 41 } 42 } 43 }

 

Java之JDBC操作

标签:next   root   rac   static   rom   ace   com   tor   mysq   

人气教程排行