Java数据库编程:JDBC详解
Java数据库编程:JDBC详解
概述
JDBC(Java Database Connectivity)是Java访问数据库的标准API。通过JDBC,Java程序可以连接各种关系型数据库,执行SQL语句,处理结果集。
1. JDBC连接
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "123456";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("数据库连接成功");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2. CRUD操作
import java.sql.*;
public class UserDAO {
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "123456");
}
public User findById(int id) {
String sql = "SELECT * FROM users WHERE id = ?";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return new User(rs.getInt("id"), rs.getString("name"), rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public int insert(User user) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, user.getName());
stmt.setString(2, user.getEmail());
return stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}
3. 事务管理
import java.sql.*;
public class TransactionDemo {
public void transfer(int fromId, int toId, double amount) {
Connection conn = null;
try {
conn = getConnection();
conn.setAutoCommit(false);
String debitSql = "UPDATE accounts SET balance = balance - ? WHERE id = ?";
PreparedStatement debitStmt = conn.prepareStatement(debitSql);
debitStmt.setDouble(1, amount);
debitStmt.setInt(2, fromId);
debitStmt.executeUpdate();
String creditSql = "UPDATE accounts SET balance = balance + ? WHERE id = ?";
PreparedStatement creditStmt = conn.prepareStatement(creditSql);
creditStmt.setDouble(1, amount);
creditStmt.setInt(2, toId);
creditStmt.executeUpdate();
conn.commit();
System.out.println("转账成功");
} catch (SQLException e) {
if (conn != null) {
try { conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(); }
}
e.printStackTrace();
} finally {
if (conn != null) {
try { conn.setAutoCommit(true); conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
}
4. 批处理
public void batchInsert(List<User> users) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
conn.setAutoCommit(false);
for (User user : users) {
stmt.setString(1, user.getName());
stmt.setString(2, user.getEmail());
stmt.addBatch();
}
stmt.executeBatch();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
最佳实践
- 使用PreparedStatement:防止SQL注入
- 使用try-with-resources:自动关闭资源
- 使用连接池:提高性能
- 事务管理:保证数据一致性
- 批处理:提高批量操作效率
总结
JDBC是Java访问数据库的基础,掌握连接、CRUD操作、事务管理和批处理,是开发数据库应用的关键。合理使用PreparedStatement和连接池,可以提高应用的性能和安全性。