Java Learning----JDBC---Placing database connection information in a configuration file

Source: Internet
Author: User

The directory is as follows:

Jdbcconnection.java:

Package Jdbc01;import Java.io.inputstream;import Java.sql.connection;import java.sql.driver;import Java.util.properties;import org.junit.test;/** * Decoupling the JDBC connection into the configuration file * @author Sawshaw * */public class jdbcconnection{ public static void Main (string[] args) {}public Connection getconnection () throws Exception{string Driverclass=null; String Jdbcurl=null; String User=null; String Pwd=null;inputstream In=getclass (). getClassLoader (). getResourceAsStream ("jdbc01/sql.properties");// System.out.println ("File Address:" +getclass (). getClassLoader (). GetResource ("jdbc01/sql.properties"));// System.out.println ("File Address:" +getclass (). getClassLoader (). Getsystemresource ("jdbc01/sql.properties")); Properties Properties=new Properties ();p roperties.load (in);d riverclass=properties.getproperty ("Driver"); jdbcurl= Properties.getproperty ("url"), User=properties.getproperty ("user");p wd=properties.getproperty ("pwd");//forname Returns a class that Newinstance creates an object driver driver= (driver) class.forname (driverclass). newinstance (); Properties info=new PrOperties (); Info.put ("User", user), Info.put ("password", pwd); Connection Connection=driver.connect (Jdbcurl, info); return Connection; } @Test public void Testconnection () throws Exception{system.out.println (Getconnection ());}}

Sql.properties:

Driver=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306/testuser=rootpwd=root

Pass with JUnit test, connection successful ...

 

Java Learning----JDBC---Placing database connection information in a configuration file

Related Article

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.