Driver:
Package Xuezaipiao;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import java.io.IOException; Import Java.sql.connection;import java.sql.driver;import Java.sql.sqlexception;import java.util.Properties;public Class Getdabseconnection {public static void main (string[] args) {System.out.println (getconnection ());} private static Connection getconnection () {//1. Get local Configuration file Properties Properties = new properties (); try {properties.load ( New FileInputStream ("D://learnjava//learnjdbc//src//jdbc.properties"));} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} String drivername = properties.getproperty ("Driver");//2. Create database-driven driver Driver = null;try {driver = (driver) Class.forName (drivername). newinstance ();//Reflection Create} catch (Instantiationexception e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace ();} catch (ClassNotFoundException e) {e.printstacktrace ();} 3. Get configuration information String user = Properties.getproperty ("user"); String password = properties.getproperty ("password"); String Jdbcurl = Properties.getproperty ("Jdbcurl"); Properties Info = new properties (), Info.put ("user", user), Info.put ("password", password);//4. Database Connection Connection Connection = null;try {connection = Driver.connect (Jdbcurl, info);} catch (SQLException e) {e.printstacktrace ();} return connection;}}
Jdbc.properties
#oracledriver =oracle.jdbc.driver.oracledriverjdbcurl=jdbc:oracle:thin: @localhost: 1521:orcluser=scottpassword= qiaolezi#mysql#driverclass=com.mysql.jdbc.driver#jdbcurl=jdbc:mysql://127.0.0.1:3306/test#user=root#password= Qiaolezi
Just change the properties to get a different database connection
For Oracle database connections, take the following form:
Jdbc:oracle:thin: @localhost: 1521:sid
For SQL Server database connections, take the following form:
jdbc:microsoft:sqlserver//localhost:1433:Sid;
For MYSQL database connections, take the following form:
Jdbc:mysql://localhost:3306/sid
Ps:sid is the database name
Java Get database connection