Package Cn.liz.test;import Java.io.inputstream;import Java.sql.connection;import java.sql.driver;import Java.sql.sqlexception;import Java.util.properties;import Org.junit.test;public class JBDCtest {/** * Write a common method, Without altering the source program, can get the connection of any database * solution: The database-driven Driver implementation of the class name, URL, user, password into a * configuration file, by changing the configuration file implementation and detailed database decoupling. * @throws Exception */public Connection getconnection () throws exception{string Driverclass = null; String jdbcurl = null; String user = null; String password = null;//reads the jdbc.properties file under the classpath inputstream in = GetClass (). getClassLoader (). getResourceAsStream (" Jdbc.properties "); Properties Properties = new properties ();p roperties.load (in);d Riverclass = Properties.getproperty ("Driver"); Jdbcurl = Properties.getproperty ("Jdbcurl"), user = Properties.getproperty ("user");p Assword = Properties.getproperty (" Password ");//By reflecting common Driver objects. Driver Driver = (Driver) class.forname (Driverclass). newinstance (); Properties Info = new properties (), Info.put ("user", user), Info.put ("PassWOrd ", password);//Get a database connection through the Driver connect method. Connection Connection = Driver.connect (Jdbcurl, info); return Connection;} @Testpublic void Testgetconnection () throws Exception{system.out.println (Getconnection ());}} <span style= "White-space:pre" ></span>
<span style= "font-family:arial, Helvetica, Sans-serif;" >jdbc.properties</span> configuration file:
#driver =oracle.jdbc.driver.oracledriver#jdbcurl=jdbc:oracle:thin: @localhost: 1521:orcl#user=scott#password= javadriver=com.mysql.jdbc.driverjdbcurl=jdbc:mysql://localhost:3306/testuser=rootpassword=
Java uses JDBC to connect to the arbitrary type database (MySQL Oracle. )