Java uses JDBC to connect to any type of database (mysqloracle ..) _ MySQL

Source: Internet
Author: User
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=

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.