Java Get database Connection __ Database

Source: Internet
Author: User

/**

*connectionutil. java

*

*

*/

Package COM.CAI.JDBC;

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.util.Properties;

public class Connectionutil {
/**
* 1
* Curing the connection parameters in the method
* @return Database connection
*/
Public Connection getconnection () {
Connection conn = null;
try{
Class.forName ("Com.mysql.jdbc.Driver");

conn = Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/stud", "root", "root");

Return conn;

}catch (Exception e) {
E.printstacktrace ();
}
return null;
}

/**
* 2
* Passing connection parameters by means of parameter
* @return Database connection
*/
Public Connection getconnection (string driver, string URL, string user, string password) {

Connection conn = null;

try{
Class.forName (driver);
conn = drivermanager.getconnection (URL, user, password);

Return conn;

}catch (Exception e) {
E.printstacktrace ();
}

return null;
}

/**
* 3
* Flexible configuration of connection parameters through the properties configuration file, property name curing
* @return Database connection
*/
Public Connection OpenConnection () {

Connection conn = null;
String driver = "";
String url = "";
String user = "";
String password = "";
Properties Props = new properties ();
try{
Props.load (This.getclass (). getClassLoader (). getResourceAsStream ("dbconfig.properties"));
Driver = Props.getproperty ("Driver");
url = props.getproperty ("url");
user = Props.getproperty ("user");
Password = props.getproperty ("password");

Class.forName (driver);
conn = drivermanager.getconnection (URL, user, password);

Return conn;
}catch (Exception e) {
E.printstacktrace ();
}

return null;
}

public static void Main (String []args) {
Connectionutil cu = new Connectionutil ();

System.out.println ("1 、---->" + cu.getconnection ());
System.out.println ("2 、---->" + cu.getconnection ("Com.mysql.jdbc.Driver")
"Jdbc:mysql://localhost:3306/stud", "root", "root"));
System.out.println ("3 、---->" + cu.openconnection ());

}


}

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.