JDBC 快速入门
一、JDBC是什么?
JDBC是Sun公司提供的 一套通用的用于数据库操作的接口,独立于特定数据库管理系统。而不同的数据库厂商针对这套接口,提供的不同实现,即为不同的数据库驱动。
二、JDBC用来干什么?
JDBC定义了一套用来访问数据库的标准Java类库,使用这些类库可以方便地访问数据库资源。简言之:JDBC实现了通过Java语言来访问和操作数据库资源。
三、JDBC如何使用?
准备工作: 下载 mysql 的驱动 jar 包,并导入(案例采用8.0版本)
第一步: 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
第二步: 获取连接对象
String url = "jdbc:mysql://localhost:3306/db1?useSSL=false";
String username = "root";
String password = "abc123";
Connection conn = DriverManager.getConnection(url, username, password);
第三步: 定义SQL
String sql = "update emp set salary = 2000 where id = 1";
第四步: 获取执行SQL的对象
Statement stmt = conn.createStatement();
第五步: 执行SQL
int count = stmt.executeUpdate(sql);
第六步: 处理结果
System.out.println(count);
最后一步: 释放资源
stmt.close();
conn.close();
四、?: 当数据库的信息采用外部文件书写时,应该如何进行改动?
jdbc.properties 具体内容为:
user=root password=abc123 url=jdbc:mysql://localhost:3306/db1?useSSL=false className=com.mysql.cj.jdbc.Driver
注意:properties文件放在resources目录下
代码演示:
//1. 加载配置文件
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties info = new Properties();
info.load(is);
//2. 获取配置信息
String url = info.getProperty("url");
String user = info.getProperty("user");
String password = info.getProperty("password");
String className = info.getProperty("className");
//3. 加载驱动
Class.forName(className);
//4. 获取连接
Connection conn = DriverManager.getConnection(url, user, password);
//5. 编写SQL
String sql = "update employee set salary = 2000 where id = 10001";
//6. 获取执行SQL的对象
Statement stmt = conn.createStatement();
//7. 执行SQL
int count = stmt.executeUpdate(sql);
System.out.println(count);
//8. 资源关闭
stmt.close();
conn.close();