java连接mysql数据库
时间: 2023-07-11 08:54:48 浏览: 29
连接 MySQL 数据库需要使用 JDBC(Java 数据库连接)API。以下是连接 MySQL 数据库的基本步骤:
1. 导入 JDBC API 的类和 MySQL 驱动程序的类。
2. 使用 `Class.forName()` 方法加载 MySQL 驱动程序的类。
3. 使用 `DriverManager.getConnection()` 方法建立与数据库的连接。
4. 使用 `Connection` 对象创建 `Statement` 对象。
5. 使用 `Statement` 对象执行 SQL 查询或更新。
6. 关闭 `Statement` 和 `Connection` 对象。
以下是一个连接 MySQL 数据库并执行查询的示例代码:
```java
import java.sql.*;
public class MySQLExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 导入 JDBC API 和 MySQL 驱动程序的类
Class.forName("com.mysql.jdbc.Driver");
// 建立与数据库的连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行查询
rs = stmt.executeQuery("SELECT * FROM mytable");
// 处理查询结果
while (rs.next()) {
System.out.println(rs.getString("column1") + "\t" + rs.getString("column2"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
// 关闭 ResultSet、Statement 和 Connection 对象
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
其中,`jdbc:mysql://localhost:3306/mydatabase` 是数据库的连接字符串,`username` 和 `password` 分别是数据库的用户名和密码。在实际代码中,应该将它们替换为正确的值。