如何连接mysql数据库
时间: 2023-11-15 10:07:14 浏览: 50
连接MySQL数据库可以通过Java中的JDBC API来实现。具体步骤如下:
1. 导入MySQL的驱动程序,可以通过在代码中手动注册驱动或者使用Class.forName()方法自动注册驱动。
2. 构造连接字符串,包括数据库的IP地址、端口号、数据库名、用户名和密码等信息。
3. 使用DriverManager.getConnection()方法获取数据库连接对象。
4. 使用连接对象进行数据库操作。
以下是一个示例代码:
```
import java.sql.*;
public class MySQLConnection {
public static void main(String[] args) {
Connection conn = null;
try {
// 注册MySQL驱动
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();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
相关推荐
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)