Java如何连接数据库?
时间: 2024-05-31 19:05:28 浏览: 15
Java连接数据库主要使用JDBC(Java Database Connectivity)技术。JDBC是Java程序访问数据库的标准API,可用于连接各种关系型数据库,如MySQL、Oracle、SQL Server等。
以下是Java连接数据库的基本步骤:
1. 加载数据库驱动程序。
2. 建立数据库连接。
3. 创建Statement或PreparedStatement对象。
4. 执行SQL语句并处理结果。
5. 关闭连接、释放资源。
下面是一个简单的Java连接MySQL数据库的例子:
```
import java.sql.*;
public class Test {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载MySQL驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 创建Statement对象
stmt = conn.createStatement();
// 执行SQL语句
String sql = "SELECT * FROM student";
rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接、释放资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```