JDBC连接数据库的步骤
- 注册驱动
- 获取连接对象
- 创建SQL语句
- 创建执行SQL语句的Statement对象
- 执行SQL语句
- 释放资源
增删改操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false", "root", "123456"); String sql = "insert into user values (null, '行小观', '1234')"; stmt = conn.createStatement(); int i = stmt.executeUpdate(sql); System.out.println(i); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } }
if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
|
查询操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false", "root", "123456"); String username = "行小观"; String password = "1234"; String sql = "select * from user where username = '" + username + "' and password = '" + password + "'"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); float money = rs.getFloat("money"); System.out.println(id + "--" + name + "--" + money); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } }
if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
|
类的解释
1. DriverManager
(1) 通过DriverManager注册驱动
Class.forName("com.mysql.cj.jdbc.Driver")
将Driver类加载进内存。
我们翻看Driver类的源码发现静态代码块:
1 2 3 4 5 6 7 8
| static { try { DriverManager.registerDriver(new Driver()); } catch (SQLException var1) { throw new RuntimeException("Can't register driver!"); } } 复制代码
|
该静态代码块随着类被加载而执行,一旦执行,便通过DriverManager.registerDriver(new Driver())
注册驱动。
(2) 通过DriverManager获取Connection对象
1 2
| DriverManager.getConnection(url, username, password) 复制代码
|
我们只需提供三个参数:数据库的url,用户名,密码。
注意:url中需要加时区。
2. Connection
1 2
| conn.createStatement() 复制代码
|
通过Connection对象创建Statement对象
3. Statement
该对象能够执行静态SQL语句并返回执行结果。
4. ResultSet
表示数据库结果集的数据表,通常由执行查询数据库的语句生成。
可以使用next()
方法遍历结果集