java如何连接sql
连接 SQL 数据库的方法
Java 连接 SQL 数据库通常使用 JDBC(Java Database Connectivity)技术。以下是详细步骤:
1. 加载 JDBC 驱动
需要先加载对应数据库的 JDBC 驱动类。例如 MySQL 驱动:
Class.forName("com.mysql.jdbc.Driver");
2. 建立数据库连接
使用 DriverManager.getConnection() 方法建立连接,需要提供 URL、用户名和密码:
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "root";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
3. 创建 Statement 对象
通过 Connection 对象创建 Statement 或 PreparedStatement:

Statement statement = connection.createStatement();
// 或使用预编译语句
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM table WHERE id = ?");
4. 执行 SQL 查询
使用 Statement 执行 SQL 语句:
ResultSet resultSet = statement.executeQuery("SELECT * FROM table");
// 或执行更新
int rowsAffected = statement.executeUpdate("UPDATE table SET column = value WHERE condition");
5. 处理结果集
遍历 ResultSet 获取查询结果:

while(resultSet.next()) {
String column1 = resultSet.getString("column_name");
int column2 = resultSet.getInt("column_name");
}
6. 关闭连接
最后需要关闭所有资源:
resultSet.close();
statement.close();
connection.close();
使用连接池优化性能
对于生产环境,建议使用连接池管理数据库连接:
// 使用 HikariCP 连接池示例
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/database");
config.setUsername("user");
config.setPassword("password");
HikariDataSource dataSource = new HikariDataSource(config);
Connection connection = dataSource.getConnection();
异常处理
需要妥善处理 SQLException:
try {
// JDBC 操作代码
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 确保资源被关闭
}
不同数据库的 JDBC URL 格式
- MySQL:
jdbc:mysql://hostname:port/database - PostgreSQL:
jdbc:postgresql://hostname:port/database - Oracle:
jdbc:oracle:thin:@hostname:port:SID - SQL Server:
jdbc:sqlserver://hostname:port;databaseName=database






