First import the MySQL driver jar package
1. The first method
Public classDemo1 {//JDBC Protocol: Database sub-protocol://Host: Port number/connected database PrivateString url = "Jdbc:mysql://localhost:3306/test"; PrivateString user = "root"; PrivateString password = "root"; @Test Public voidtest1 () {Driver Driver=NewCom.mysql.jdbc.Driver (); Properties Props=NewProperties (); Props.setproperty ("User", user); Props.setproperty ("Password", password); Connection Conn=driver.connect (URL, props); SYSTEM.OUT.PRINTLN (conn); } }
2. The second method
Public classDemo2 {//JDBC Protocol: Database sub-protocol://Host: Port number/connected database PrivateString url = "Jdbc:mysql://localhost:3306/test"; PrivateString user = "root"; PrivateString password = "root"; @Test Public voidtest2 () {Driver Driver=NewCom.mysql.jdbc.Driver (); //1, register the driver (can register multiple programs)drivermanager.registerdriver (driver); //2. Connect to a specific databaseConnection conn =Drivermanager.getconnection (Url,user,password); SYSTEM.OUT.PRINTLN (conn); } }
Analysis of the source code of the driver class wrote
static {
try{
Java.sql.DriverManager.registerDriver (New Driver ());
}catch (SQLException e) {
throw new RuntimeException ("Can ' t Register driver!");
}
}
Static code blocks are executed when the class is loaded, so the code above is equivalent to registering two times. Improvement method Two, Method 3
3. The third method
Public classdemo3{//JDBC Protocol: Database sub-protocol://Host: Port number/connected database PrivateString url = "Jdbc:mysql://localhost:3306/test"; PrivateString user = "root"; PrivateString password = "root"; @Test Public voidTest3 ()throwsexception{Class.forName ("Com.mysql.jdbc.Driver"); Connection Conn=drivermanager.getconnection (Url,user,password); SYSTEM.OUT.PRINTLN (conn); } }
JDBC connection to MySQL database