欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java使用jdbc連接MySQL數(shù)據(jù)庫實例分析

 更新時間:2018年07月02日 09:59:48   作者:cat_pp  
這篇文章主要介紹了Java使用jdbc連接MySQL數(shù)據(jù)庫,結(jié)合實例形式分析了Java基于jdbc鏈接mysql的相關配置及工具類的定義相關操作技巧,需要的朋友可以參考下

本文實例講述了Java使用jdbc連接MySQL數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:

使用jdbc連接數(shù)據(jù)庫:

可以直接在方法中定義url、user、psd等信息,也可以讀取配置文件,但是在web項目中肯定是要使用第二種方式的,為了統(tǒng)一,只介紹第二種方式。

步驟

1、創(chuàng)建配置文件db.properties

無論是eclipse還是myeclipse,在工程下右鍵->new->file,以properties為后綴名就好了。

配置文件內(nèi)容:

#連接數(shù)據(jù)庫的url,如果主機地址是localhost,端口是3306也可以寫成url=jdbc:mysql:///databasename
url=jdbc:mysql://localhost:3306/databasename
#用戶名
user=root
#密碼
password=root
#MySQL數(shù)據(jù)庫加載驅(qū)動
driverClass=com.mysql.jdbc.Driver

2、定義一個使用jdbc連接數(shù)據(jù)庫的工具類JdbcUtil.java

工具類內(nèi)容:

public class JdbcUtil{
 //定義全局變量
 private static String url = null;
 private static String user = null;
 private static String password = null;
 private static driverClass = null;
 //讀取配置文件內(nèi)容,放在靜態(tài)代碼塊中就行,因為只需要加載一次就可以了
 static{
  try{
   Properties props = new Properties();
   //使用類路徑加載的方式讀取配置文件
   //讀取的文件路徑要以“/”開頭,因為如果使用“.”的話,當部署到服務器上之后就找不到文件了,使用“/”開頭會直接定位到工程的src路徑下
   InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
   //加載配置文件
   props.load(in);
   //讀取配置文件信息
   url = props.getProperty("url");
   user = props.getProperty("user");
   password = props.getProperty("password");
   driverClass = props.getProperty("driverClass");
   //注冊驅(qū)動程序
   Class.forName(driverClass);
  }catch(Exception e){
   e.printStackTrace();
   System.out.println("驅(qū)動程序注冊失?。。。?);
  }
 }
 //獲取連接對象Connection
 public static Connection getConnection(){
  try{
   return DriverManager.getConnection(url,user,password);
  }catch(SQLException e){
   e.printStackTrace();
   //跑出運行時異常
   throw new RuntimeException();
  }
 }
 //關閉連接的方法,后打開的先關閉
 public static void close(Connection conn,Statement stmt,ResultSet rs){
  //關閉ResultSet對象
  if(rs != null){
   try{
    //關閉rs,設置rs=null,因為java會優(yōu)先回收值為null的變量
    rs.close();
    rs = null;
   }catch(SQLException e){
    e.printStackTrace();
    throw new RuntimeException();
   }
  }
  //關閉Statement對象,因為PrepareStatement和CallableStatement都是Statement的子接口,所以這里只需要有關閉Statement對象的方法就可以了
  if(stmt != null){
   try{
    stmt.close();
    stmt = null;
   }catch(SQLException e){
    e.printStackTrace();
    throw new RuntimeException();
   }
  }
  //關閉Connection對象
  if(conn != null){
   try{
    conn.close();
    conn = null;
   }catch(SQLException e){
    e.printStackTrace();
    throw new RuntimeException();
   }
  }
 }
}

可以聊任何java問題,JavaSE、JavaEE

工具類已經(jīng)實現(xiàn)了,可以直接考到項目里使用,但是有一點要注意,就是這個類文件中沒有導入支持的類,大家也可以看到在類的頭部沒有package import,這個需要自己手動添加上,導入類的快捷鍵是Ctrl+Shift+O,導包的時候不要導錯了;別忘了引入MySQL的支持jar包mysql-connector-java-5.1.7-bin.jar

附:mysql-connector-java-5.1.7-bin.jar可點擊此處本站下載

更多關于java相關內(nèi)容感興趣的讀者可查看本站專題:《Java+MySQL數(shù)據(jù)庫程序設計總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java文件與目錄操作技巧匯總》、《Java操作DOM節(jié)點技巧總結(jié)》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設計有所幫助。

相關文章

最新評論