Get the driver for MySQL for Java and add it to your project
Access the following URL and set the select box under Select Operating System:
to Platform Independent
Download the zip and unzip it. (Download destination is OK anywhere)
SQL Driver
After unzipping, you will have a jar file
.
Add the unzipped SQL driver to your project.
ʻDrag and drop to WebContent-> WEB-INF-> lib
of the project created with Eclipse`
It becomes as follows.
Open `` Project right-click-> Build path-> Build path configuration, select
Add external JAR from the Library tab, and add the jar to
WebContent-> WEB-INF-> lib` earlier. Select a file and let it be added.
The screen when added is as follows.
Make a DB connection with the following implementation
DBConnect.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBManager {
public static Connection getConnection(){
Connection con = null; //Initialization
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:port number/Database name","username","password");
System.out.println("DB connection successful!!!");
return con;
}catch(ClassNotFoundException e){
throw new IllegalMonitorStateException(); //Exception handling when there is no class
} catch (SQLException e) {
throw new IllegalMonitorStateException(); //Exception handling when an error occurs in SQL
}
}
}
DBConnect.java
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:port number/Database name","username","password");
System.out.println("DB connection successful!!!"); //It is OK even if it is not designed to output if it succeeds
return con; //Returns the connection result
Class.forName("com.mysql.jdbc.Driver");
Class Class ... w
A method called getClass () is implemented in the java.lang.Object class, which is a superclass of all classes, and class information of the corresponding subclass is generated and held as an instance of the Class class when the subclass is instantiated. ..
Is it an image like a class for reading classes?
forName("com.mysql.jdbc.Driver"); The class name in parentheses is the SQL driver specified here.
forName () loads the DB driver class and runs the static initializer. All DB driver classes implement java.sql.Driver, and each DB driver class carries out the process of registering the DB driver class itself in the class that manages the driver called DriverManager class with the static initializer. I will.
It seems that forName
will go to find the SQL driver and register it without permission
Reference: Class class that seems to be known but not known (basic)
This completes the DB connection.
Recommended Posts