最原始的jdbc代码

后期的开发中我们经常会用到各种各样的框架,可能最原始的jdbc我们就用不到了,但是我们不应该忘记最原始的写法:

 1 @Test
 2     public void testJDBC() {
 3         Connection conn = null;
 4         PreparedStatement psmt = null;
 5         ResultSet rs = null;
 6         //加载驱动
 7         try {
 8             Class.forName("com.mysql.jdbc.Driver");
 9             //创建连接
10             conn = DriverManager.getConnection("jdbc:mysql:///spring_day03", "root", "root");
11             //编写sql语句
12             String sql = "select * from user where username=?";
13             //预编译sql
14             psmt = conn.prepareStatement(sql);
15             //设置参数值
16             psmt.setString(1, "lucy");
17             //执行sql
18             rs = psmt.executeQuery();
19             //遍历结果集
20             while(rs.next()) {
21                 //得到返回结果值
22                 String username = rs.getString("username");
23                 String password = rs.getString("password");
24                 //放到user对象里面
25                 User user = new User();
26                 user.setUsername(username);
27                 user.setPassword(password);
28                 
29                 System.out.println(user);
30             }
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     }

框架只是帮我们封装好了一部分代码,底层的我们还是要清楚的。

原文地址:https://www.cnblogs.com/cuibin/p/6713209.html