第一步:pom.xml中添加依赖;
mysql
mysql-connector-java
第二步:编写连接类
package com.example.demo.controller;
import java.lang.*;
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/mysql?serverTimezone=GMT%2B8";
// String url = "jdbc:mysql://127.0.0.1:3306/mysql";
Connection con = DriverManager.getConnection(url, "root", "123");
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery("select * from db");
while(resultSet.next()){
System.out.println(resultSet.getString(1));
}
}
}
执行结果:
注:问题记录
1.数据库密码错误会报错“Exception in thread "main" java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)”
2.url中未加参数‘serverTimezone=GMT%2B8’,会报下面的错误;
3.mysql驱动,使用
"com.mysql.jdbc.Driver"
会报如下警告:
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
换成
"com.mysql.cj.jdbc.Driver"
即可
标签:jdbc,java,springboot,MySQL,Driver,mysql,com,class
来源: https://blog.csdn.net/qq516071744/article/details/86499027