推荐文章:
步骤:
- 找到MySQL的连接Java的jar文件;
如下图:
- 在eclipse项目文件下找到lib文件夹,没有的话就自己创建一个,然后将上面找到的jar文件复制粘贴到lib文件夹的下面;
如下图:
- 给这个jar文件构建路径;
右键jar文件 -> 构建路径(Build Path)-> 配置并构建路径(Add to Build Path);
您现在应该生成一个引用库,如下所示:[En]
You should now generate a referenced library, as shown below:
进入eclipse类中编写代码:
-
导入sql:import java.sql.*;
- 加载驱动:
先定义常量:
MySQL 8.0以下版本:static final String JDBC_DRIVER = “com.mysql.jdbc.Driver”;
MySQL 8.0及以上版本:static final String JDBC_DRIVER = “com.mysql.cj.jdbc.Driver”;
再加载:
Class.forName(JDBC_DRIVER); - 连接数据库:
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
三个参数分别是数据库url,用户名,密码
数据库url示例:
MySQL 8.0以下版本:static final String DB_URL = “jdbc:mysql://localhost:3306/testdb”;
MySQL 8.0及以上版本:static final String DB_URL = “jdbc:mysql://localhost:3306/testdb?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC”;
其中testdb为自己创建的数据库的名称;
用户名和对应的密码是在创建数据库时设置的,例如:[En]
The user name and corresponding password are set when you create the database, such as:
static final String USER = “root”;
static final String PASS = “123321”; - 通过这种方式,数据库连接成功,可以进行下一步。
[En]
in this way, the database is successfully connected and can proceed to the next step.*
完整代码给出如下:
点击查看代码
package com.runoob.test;
import java.sql.*;
public class MySQLDemo {
static final String JDBC_DRIVE = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/testdb?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "123321";
public static void main(String[] args){
Connection conn = null;
try {
Class.forName(JDBC_DRIVE);
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("实例化Statement对象...");
conn.close();
System.out.println("数据库断开连接");
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(conn!=null)conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
Original: https://www.cnblogs.com/APiceland/p/16249915.html
Author: APiceland
Title: eclipse连接MySQL 8.0.29.0
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/505395/
转载文章受原作者版权保护。转载请注明原作者出处!