第一步:下载mysql驱动包
1、mysql官网:https://dev.mysql.com/downloads/connector/j/
2、此时会进入下载页面,无需登录,直接下载即可,如下图所示:
3、mysql-connector-j-8.0.32.zip下载成功,里面含有mysql-connector-j-8.0.32.jar文件,后续使用。
第二步:在JAVA项目中新建lib文件夹,将mysql-connector-j-8.0.32.jar放进去,右击lib文件夹,选择“添加到库”;
第三步:编写连接MYSQL的类文件,示例如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ConnMySql { public static void main(String[] args) throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); try ( Connection conn = DriverManager.getConnection( "jdbc:mysql://127.0.0.1:3306/xyytest", "root", "HUawei123"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select *" + " from employees" + " where department_id in ('10','20','30')")) { while (rs.next()) { System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getString(4) + "\t" + rs.getString(5)); } } } }
运行时应该会报错:
Access denied for user ''root@'localhost' (using password: YES)
第四步:修改my.ini文件,在[mysqlid] 下面添加一句 skip-grant-tables,这个是为了跳过登陆的,不用密码也能进mysql。
登录mysql服务器,
先输入:flush privileges;
再输入:ALTER USER 'root'@'localhost' IDENTIFIED BY '密码';
如下图:
第五步:重下运行java程序即可