When we use java to operate MySQL database in idea, the following results will appear:
Exception in thread “main” java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader. java:382 )
at java.lang.ClassLoader.loadClass(ClassLoader. java:418 )
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher. java:355 )
at java.lang.ClassLoader.loadClass(ClassLoader. java:351 )
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class. java:264 )
at src.mySql.Jdbc.main(Jdbc. java:10 )
1、 General solution
1. JDBC download link
https://dev.mysql.com/downloads/connector/j/
2. Select the content to download and download it
Select platform independent as the operating system. For the two records in the list below, the suffix tar.gz is the Linux version and the suffix. Zip is the Windows version
Here, download the jdbc driver of Windows version, version 8.0.18
Skip login and click the content in the red box to download
3. Import driver into Java project
In idea, click file — project structure
Module, dependencies tab
Click the plus sign (+) on the far right and select jars or directions
2、 Still import driver failed
1. In idea, click file — project structure
2. Select the SDKs, click the plus sign (+) on the far right, select the jdbc driver of Windows version we downloaded before, and then click OK to confirm
3. Finally, we can use this driver by connecting to MySQL database on the idea
Example:
package src.mySql;
import java.sql.*;
public class Jdbc {
public static void main(String[] args) throws Exception {
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
long start = System.currentTimeMillis();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1",
"root", "root");
long end = System.currentTimeMillis();
System.out.println(conn);
System.out.println("Time to establish connection: " + (end - start) + "ms milliseconds");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Results: the results were as follows