java连接数据库mysql-connector-java-8.0.20
时间: 2023-08-25 22:07:54 浏览: 149
要使用Java连接MySQL数据库,需要下载并安装MySQL Connector/J驱动程序。以下是安装步骤:
1. 访问MySQL官方网站,下载MySQL Connector/J驱动程序。当前最新版本为8.0.20,下载地址为:https://dev.mysql.com/downloads/connector/j/
2. 下载后,将mysql-connector-java-8.0.20.jar文件复制到项目的classpath路径下。
3. 在Java代码中添加连接MySQL数据库的代码,示例代码如下:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnect {
public static void main(String[] args) {
Connection conn = null;
try {
// 加载MySQL驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取数据库连接
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "root";
conn = DriverManager.getConnection(url, user, password);
System.out.println("数据库连接成功!");
} catch (SQLException e) {
System.out.println("数据库连接失败:" + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("找不到MySQL驱动程序:" + e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("关闭数据库连接失败:" + e.getMessage());
}
}
}
}
```
以上代码演示了如何连接本地MySQL数据库,如果需要连接远程MySQL数据库,只需要将url中的localhost改为远程MySQL服务器的IP地址即可。同时,需要确保远程MySQL服务器已经允许远程连接。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.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)
![](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)