java连接mysql数据库
时间: 2023-06-30 16:04:55 浏览: 45
要连接 MySQL 数据库,需要使用 JDBC 驱动程序。以下是 Java 连接 MySQL 数据库的步骤:
1. 下载 MySQL JDBC 驱动程序:你可以从 MySQL 官方网站下载 MySQL Connector/J 驱动程序,或者使用 Maven、Gradle 等构建工具进行下载。
2. 加载驱动程序:在 Java 代码中,使用 `Class.forName()` 方法加载 MySQL JDBC 驱动程序。
3. 建立连接:使用 `DriverManager.getConnection()` 方法建立与 MySQL 数据库的连接。需要提供 MySQL 数据库的 URL、用户名和密码。
4. 执行 SQL 语句:使用 `Connection.createStatement()` 方法创建一个 Statement 对象,然后使用该对象的 `executeQuery()` 或 `executeUpdate()` 方法执行 SQL 语句。
5. 处理结果集:如果执行的 SQL 语句返回结果集,使用 ResultSet 对象处理结果集。
以下是一个示例代码:
```java
import java.sql.*;
public class MySQLExample {
public static void main(String[] args) {
try {
// 加载MySQL JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立MySQL数据库连接
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "username", "password");
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行查询语句
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// 遍历结果集
while (rs.next()) {
System.out.println(rs.getString("name") + " " + rs.getString("email"));
}
// 关闭结果集、Statement和连接
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,需要将 `localhost:3306/mydb` 替换为你的 MySQL 数据库的 URL,`username` 和 `password` 分别替换为你的 MySQL 数据库的用户名和密码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)