运用jdbc连接数据库可以分为六步:
1、加载驱动
2、创建连接
3、创建语句
4、执行语句
5、处理返回结果
6、关闭资源
注意:导入包的时候要导入sql下的包不要jdbc下的
1 private static void jdbc() throws ClassNotFoundException, SQLException { 2 String driver="com.mysql.jdbc.Driver"; 3 String url = "jdbc:mysql://localhost:3306/mydata?useUnicode=true&characterEncoding=UTF-8"; 4 //mydata:是数据库名 ?和后面的语句是设置编码为UTF-8 5 String user = "root"; 6 String password="1234"; 7 //1、加载驱动 8 Class.forName(driver); 9 //2、创建连接 10 Connection conn = DriverManager.getConnection(url, user, password); 11 //3、创建语句 12 String sql = "select * from t_book"; 13 PreparedStatement ps = conn.prepareStatement(sql); 14 //4、执行语句 15 ResultSet rs = ps.executeQuery(); 16 //5、处理结果 17 List<Book> list = new ArrayList<>(); 18 while (rs.next()) { 19 Book book = new Book(rs.getInt("bid"), rs.getString("bname"), rs.getDouble("bprice"), 20 rs.getDate("bdate"), rs.getString("btext")); 21 list.add(book); 22 } 23 //6、关闭资源(后打开的资源要先关闭) 24 rs.close(); 25 ps.close(); 26 conn.close(); 27 }
原文:https://www.cnblogs.com/lingdu9527/p/11006443.html