java连接mysql数据库的代码
时间: 2023-06-22 15:40:11 浏览: 62
以下是Java连接MySQL数据库的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
public static void main(String[] args) {
// MySQL数据库的JDBC驱动程序
String driver = "com.mysql.cj.jdbc.Driver";
// 数据库连接的URL
String url = "jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
// 数据库的用户名和密码
String user = "root";
String password = "123456";
Connection conn = null;
try {
// 加载MySQL的JDBC驱动程序
Class.forName(driver);
// 建立数据库连接
conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
System.out.println("数据库连接成功!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的示例代码中,使用了MySQL的JDBC驱动程序,连接的数据库是本地的MySQL数据库,用户名为root,密码为123456,连接的数据库名为mydatabase。需要注意的是,要根据实际情况修改连接的URL和用户名密码。
相关推荐
![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)
![](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)