Java连接SQL数据库的方法有哪些详细步骤?
- 数据库
- 2025-11-09
- 5
在Java中与SQL数据库连接,通常需要使用JDBC(Java Database Connectivity)API,以下是使用JDBC连接数据库的详细步骤:
准备工作
在开始之前,请确保以下条件已满足:

- 数据库:您需要有一个运行的数据库,如MySQL、Oracle、PostgreSQL等。
- JDBC驱动:您需要下载对应数据库的JDBC驱动程序,并将其添加到项目的类路径中。
- Java环境:确保您的计算机上已安装Java开发工具包(JDK)。
加载JDBC驱动
您需要加载JDBC驱动程序,这可以通过使用Class.forName()方法完成。
try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); }
建立数据库连接
使用DriverManager.getConnection()方法建立与数据库的连接,您需要提供以下信息:
- 数据库URL:指定数据库的地址和名称。
- 用户名:数据库的用户名。
- 密码:数据库的密码。
String url = "jdbc:mysql://localhost:3306/数据库名称"; String user = "用户名"; String password = "密码"; Connection connection = null; try { connection = DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); }
创建Statement或PreparedStatement
一旦建立了连接,您可以使用connection.createStatement()或connection.prepareStatement()创建Statement或PreparedStatement对象,这两个对象用于执行SQL语句。

Statement statement = null; PreparedStatement preparedStatement = null; try { statement = connection.createStatement(); preparedStatement = connection.prepareStatement("SELECT * FROM 表名"); } catch (SQLException e) { e.printStackTrace(); }
执行SQL语句
使用Statement或PreparedStatement对象的executeQuery()方法执行查询语句,或executeUpdate()方法执行更新、插入或删除语句。
ResultSet resultSet = null; try { resultSet = statement.executeQuery("SELECT * FROM 表名"); while (resultSet.next()) { // 处理结果集 } } catch (SQLException e) { e.printStackTrace(); }
关闭连接
在完成数据库操作后,请确保关闭所有资源,包括ResultSet、Statement和Connection。

try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (preparedStatement != null) preparedStatement.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); }
表格示例
| 步骤 | 代码示例 |
|---|---|
| 加载JDBC驱动 | Class.forName("com.mysql.cj.jdbc.Driver"); |
| 建立数据库连接 | Connection connection = DriverManager.getConnection(url, user, password); |
| 创建Statement | Statement statement = connection.createStatement(); |
| 创建PreparedStatement | PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM 表名"); |
| 执行SQL语句 | ResultSet resultSet = statement.executeQuery("SELECT * FROM 表名"); |
| 关闭连接 | try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (preparedStatement != null) preparedStatement.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } |
FAQs
Q1:如何处理SQL载入攻破?
A1:为了防止SQL载入攻破,您应该使用PreparedStatement而不是Statement。PreparedStatement允许您在SQL语句中使用参数占位符,这样就可以避免将用户输入直接拼接到SQL语句中。
Q2:如何处理异常?
A2:在JDBC中,所有数据库操作都可能抛出SQLException,您应该使用trycatch块捕获这些异常,并适当处理它们,您可以记录异常信息、向用户显示错误消息或尝试执行其他错误恢复操作。