JAVA如何连接数据库
时间: 2024-03-24 20:35:57 浏览: 7
JAVA 可以通过 JDBC 技术连接数据库,具体步骤如下:
1. 加载数据库驱动程序:使用 Class.forName() 方法加载数据库驱动程序。
2. 建立数据库连接:通过 DriverManager.getConnection() 方法获取数据库连接对象。
3. 创建 Statement 对象:通过 Connection.createStatement() 方法创建 Statement 对象,用于执行 SQL 语句。
4. 执行 SQL 语句:使用 Statement 对象执行 SQL 语句,如查询、插入、更新等操作。
5. 处理结果集:使用 ResultSet 对象处理查询结果集。
6. 关闭数据库连接:使用 Connection.close() 方法关闭数据库连接。
以下是一个简单的示例代码:
```
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行 SQL 语句
String sql = "SELECT * FROM user";
rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
} catch (Exception 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();
}
}
}
}
```