java中怎么连接数据库
时间: 2023-07-03 15:32:44 浏览: 43
在Java中连接数据库通常需要以下步骤:
1. 加载数据库驱动程序
2. 使用JDBC API建立数据库连接
3. 创建一个Statement对象用于执行SQL语句
4. 执行SQL语句并处理结果
5. 关闭数据库连接
以下是一个连接MySQL数据库的示例代码:
```java
import java.sql.*;
public class ConnectMySQL {
public static void main(String args[]) {
try {
// 加载MySQL驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行SQL语句
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
// 处理结果
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
```
在以上代码中,我们首先加载MySQL驱动程序,然后使用`DriverManager.getConnection`方法建立数据库连接。接着创建Statement对象,执行SQL语句并处理结果。最后关闭数据库连接。