Package COM.ATGUIGU.JDBC;
Import java.io.IOException;
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 Jdbctest {
/**
* Write a common method to get a connection to any database without modifying the source program
* Solution: The full class name, URL, User\password of the database-driven driver implementation class are put into a configuration file and implemented by modifying the configuration file
* Decoupled from the specific database
* @throws ClassNotFoundException
* @throws illegalaccessexception
* @throws instantiationexception
* @throws SQLException
* @throws IOException
*/
Public Connection getconnection () throws Instantiationexception, Illegalaccessexception, ClassNotFoundException, SQLException, ioexception{
String driverclass=null;
String Jdbcurl=null;
String User=null;
String Password=null;
//Read Jdbc.properties file under Classpath
InputStream in=getclass (). getClassLoader (). getResourceAsStream (" Jdbc.properties ");
Properties Properties=new properties ();
Properties.load (in);
Driverclass=properties.getproperty ("Driverclass");
Jdbcurl=properties.getproperty ("Jdbcurl");
User=properties.getproperty ("user");
Password=properties.getproperty ("password");
//Create a Driver object by reflection
Driver driver= (Driver) class.forname (Driverclass). newinstance ();
Properties Info=new properties ();
Info.setproperty ("user", user);
Info.setproperty ("password", password);
//Get a database connection through the driver Connect method
Connection connection=driver.connect (Jdbcurl, info);
return connection;
}
@Test
public void Testgetconnection () throws Instantiationexception, Illegalaccessexception, ClassNotFoundException, SQLException, ioexception{
System.out.println (getconnection ());
}
}
To create a connection object by reading the database settings information in the configuration file