代碼如下所示:
代碼如下:
/**
*ConnectionUtil .java
*
*
*/
package com.cai.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties ;
public class ConnectionUtil {
/**
* 1
*在方法中固化連接參數
* @return 數據庫連接
*/
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
*通過方法參數方式傳遞連接參數
* @return 數據庫連接
*/
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
*通過properties配置文件的方式靈活配置連接參數,properties中的屬性名固化
* @return 數據庫連接
*/
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()) ;
}
}