java连接mysql数据库代码
时间: 2023-06-21 16:14:21 浏览: 60
以下是一个简单的Java程序,用于连接MySQL数据库:
```java
import java.sql.*;
public class MySQLConnect {
public static void main(String[] args) {
Connection conn = null;
try {
// 加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
System.out.println("成功连接到数据库!");
}
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动程序:" + e.getMessage());
} catch (SQLException e) {
System.out.println("无法连接数据库:" + e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
System.out.println("成功关闭数据库连接!");
}
} catch (SQLException e) {
System.out.println("无法关闭数据库连接:" + e.getMessage());
}
}
}
}
```
请注意,您需要在代码中更改以下变量以便与您的数据库匹配:
- `url`:数据库的URL。
- `user`:您的MySQL用户名。
- `password`:您的MySQL密码。
相关推荐
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)