国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java 獲取數(shù)據(jù)庫連接的實(shí)現(xiàn)代碼

2019-11-26 16:04:43
字體:
供稿:網(wǎng)友
代碼如下所示:
復(fù)制代碼 代碼如下:

/**
*ConnectionUtil .java
*
*
*/

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

 }

 
}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 历史| 长沙市| 雅江县| 涟水县| 金塔县| 柳州市| 金乡县| 芦山县| 宜川县| 贵德县| 当涂县| 永川市| 宜都市| 长葛市| 昌邑市| 静海县| 镇雄县| 渝中区| 定结县| 德阳市| 修水县| 文安县| 邹城市| 巍山| 栖霞市| 曲阜市| 黔江区| 定兴县| 深水埗区| 澄江县| 出国| 枞阳县| 苏尼特右旗| 华容县| 张家界市| 汕尾市| 宜兰市| 平阳县| 仲巴县| 曲周县| 巴林左旗|