JDBC Connection MySQL Database

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.