最常见SQL数据类型
注册驱动器
大多数jdbc的jar包都可以自动注册
手动注册的方式:注册mysql 8.0+
Class.forName("com.mysql.cj.jdbc.Driver")
连接数据库
将数据库连接值存放在database.properties,放在resources目录下
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/imooc?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
Properties properties = new Properties();
properties.load(Test1.class.getResourceAsStream("/database.properties"));
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println(connection);
}
Statement对象
ResultSet对象
管理连接、语句和结果集
SQL异常
PreparedStatement对象
防止SQL注入,但凡sql语句中有变量的都要用preparedstatement
读写LOB数据
- 读取
- 写入
多结果集
获取自动生成的键
- 使用preparedStatement
try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD)) {
try (PreparedStatement ps = conn.prepareStatement(
"INSERT INTO students (grade, name, gender) VALUES (?,?,?)",
Statement.RETURN_GENERATED_KEYS)) {
ps.setObject(1, 1); // grade
ps.setObject(2, "Bob"); // name
ps.setObject(3, "M"); // gender
int n = ps.executeUpdate(); // 1
try (ResultSet rs = ps.getGeneratedKeys()) {
if (rs.next()) {
long id = rs.getLong(1); // 注意:索引从1开始
}
}
}
}
- 使用statement
可滚动和可更新的结果集
行集RowSet
元数据
事务transaction
Connection conn = openConnection();
try {
// 关闭自动提交:
conn.setAutoCommit(false);
// 执行多条SQL语句:
insert(); update(); delete();
// 提交事务:
conn.commit();
} catch (SQLException e) {
// 回滚事务:
conn.rollback();
} finally {
conn.setAutoCommit(true);
conn.close();
}
批量更新
- preparedStatement
try (PreparedStatement ps = conn.prepareStatement("INSERT INTO students (name, gender, grade, score) VALUES (?, ?, ?, ?)")) {
// 对同一个PreparedStatement反复设置参数并调用addBatch():
for (Student s : students) {
ps.setString(1, s.name);
ps.setBoolean(2, s.gender);
ps.setInt(3, s.grade);
ps.setInt(4, s.score);
ps.addBatch(); // 添加到batch
}
// 执行batch:
int[] ns = ps.executeBatch();
for (int n : ns) {
System.out.println(n + " inserted."); // batch中每个SQL执行的结果数量
}
}
- Statement