The Code is as follows:
Copy codeThe Code is as follows :/**
* ConnectionUtil. java
*
*
*/
Package com. cai. jdbc;
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. util. Properties;
Public class ConnectionUtil {
/**
* 1
* Fixed 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
* Pass connection parameters through method parameters
* @ 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
* You can use the properties configuration file to flexibly Configure connection parameters. The property names in properties are fixed.
* @ 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 ());
}
}