Java uses JDBC to connect to any type of database (mysqloracle ..)
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 {/*** compile a common method to obtain the connection of any database without modifying the source program * solution: put the full class name, url, user, and password of the database Driver implementation class into a * configuration file, and decouple it from the specific database by modifying the configuration file. * @ throws Exception */public Connection getConnection () throws Exception {String driverClass = null; String jdbcUrl = null; String user = null; String password = null; // read the jdbc in the class path. properties file InputStream in = getClass (). getClassLoader (). getResourceAsStream ("jdbc. properties "); Properties properties = new Properties (); properties. load (in); driverClass = properties. getProperty ("driver"); jdbcUrl = properties. getProperty ("jdbcUrl"); user = properties. getProperty ("user"); password = properties. getProperty ("password"); // common Driver objects are reflected by reflection. driver driver = (Driver) Class. forName (driverClass ). newInstance (); Properties info = new Properties (); info. put ("user", user); info. put ("password", password); // Obtain the database connection through the connect method of the Driver. connection connection = driver. connect (jdbcUrl, info); return connection ;}@ Testpublic void testGetConnection () throws Exception {System. out. println (getConnection ());}}
Jdbc. properties 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=