java连接mysql数据库的代码
时间: 2023-06-23 15:57:05 浏览: 40
下面是一个基本的Java连接MySQL数据库的代码示例:
```java
import java.sql.*;
public class MySQLConnectionExample {
public static void main(String[] args) {
// MySQL数据库的JDBC驱动
String driver = "com.mysql.jdbc.Driver";
// 数据库连接地址
String url = "jdbc:mysql://localhost:3306/test";
// 数据库用户名
String username = "root";
// 数据库密码
String password = "123456";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载JDBC驱动
Class.forName(driver);
// 建立数据库连接
conn = DriverManager.getConnection(url, username, password);
// 创建Statement对象
stmt = conn.createStatement();
// 执行SQL查询语句
String sql = "SELECT id, name, age FROM user";
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 {
// 关闭ResultSet对象
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 关闭Statement对象
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 关闭数据库连接
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
在上述代码中,我们首先定义了MySQL数据库的JDBC驱动、数据库连接地址、用户名和密码等信息。然后在try语句块中,我们首先加载了MySQL数据库的JDBC驱动,然后通过DriverManager.getConnection()方法建立了数据库连接。接着创建了Statement对象,并执行了一条查询语句,将结果集保存在ResultSet对象中。最后我们遍历了结果集,取出了每一条记录的id、name和age三个字段,并打印输出。注意,在finally语句块中,我们需要关闭ResultSet、Statement和Connection对象,以避免资源泄漏。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)