1, how to get Database link connection in JDBC?
Driver is an interface: The database vendor must provide an interface for implementation. from which the database connection can be obtained.
The database connection can be obtained through the Driver implementation class object.
1. Join the MySQL Driver
1). Unzip the Mysql-connector-java-5.1.7.zip
2). Create a new Lib directory under current project
3). Copy the Mysql-connector-java-5.1.7-bin.jar to the Lib directory
4). Right-Build-path, add to BuildPath is added to the classpath. S
JDBC URLs for several common databases:
@Test Public voidTestdriver ()throwsSQLException {//1. Create an object of the Driver implementation classDriver Driver=NewCom.mysql.jdbc.Driver (); //2. Basic information about preparing a connection database: URL, user, passwordString URL= "Jdbc:mysql://localhost:3306/test"; Properties Info=NewProperties (); Info.put ("User", "root"); Info.put ("Password", "1230"); //3. Call the Connect (URL, info) of the Driver interface to get the database connectionConnection Connection=driver.connect (URL, info); System.out.println (connection);}
the simplest way to get a database link
/**jdbc.properties file: #driver =oracle.jdbc.driver.oracledriver#jdbcurl=jdbc:oracle:thin: @localhost: 1521:o Rcl#user=scott#password=javadriver=com.mysql.jdbc.driverjdbcurl=jdbc:mysql://localhost:3306/atguiguuser= rootpassword=1230*/ PublicConnection getconnection ()throwsexception{String Driverclass=NULL; String Jdbcurl=NULL; String User=NULL; String Password=NULL; //read the Jdbc.properties file under the ClasspathInputStream in =getclass (). getClassLoader (). getResourceAsStream ("Jdbc.properties"); Properties Properties=NewProperties (); Properties.load (in); Driverclass= Properties.getproperty ("Driver"); Jdbcurl= Properties.getproperty ("Jdbcurl"); User= Properties.getproperty ("User"); Password= Properties.getproperty ("Password"); //by reflecting common Driver objects.Driver Driver =(Driver) class.forname (Driverclass). newinstance (); Properties Info=NewProperties (); Info.put ("User", user); Info.put ("Password", password); //get the database connection through the Driver Connect method.Connection Connection=Driver.connect (Jdbcurl, info); returnconnection; } @Test Public voidTestgetconnection ()throwsexception{System.out.println (getconnection ()); }
A common way to get any database links without modifying the source program
Solution: Put a database-driven Driver implementation class with the full class name, URL, user, password into a
configuration file, and the specific database is decoupled by modifying the configuration file.