jdbc连接mysql5代码
时间: 2023-07-21 20:23:13 浏览: 42
以下是使用 JDBC 连接 MySQL 5 数据库的示例代码:
```java
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载 MySQL JDBC 驱动
Class.forName("com.mysql.jdbc.Driver");
// 打开连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
conn = DriverManager.getConnection(url, user, password);
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行查询
rs = stmt.executeQuery("SELECT * FROM users");
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("id: " + id + ", name: " + name);
}
} catch (ClassNotFoundException | 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();
}
}
}
}
```
在示例代码中,我们首先加载 MySQL JDBC 驱动,然后使用 DriverManager.getConnection() 方法创建一个 Connection 对象,该对象表示与数据库的连接。接下来,我们创建一个 Statement 对象,它用于执行 SQL 语句。在本例中,我们执行了一个 SELECT 查询,并使用 ResultSet 对象处理查询结果。最后,我们关闭了所有打开的资源,包括 ResultSet、Statement 和 Connection 对象。