本文實(shí)例講述了Java使用jdbc連接MySQL數(shù)據(jù)庫(kù)的方法。分享給大家供大家參考,具體如下:
使用jdbc連接數(shù)據(jù)庫(kù):
可以直接在方法中定義url、user、psd等信息,也可以讀取配置文件,但是在web項(xiàng)目中肯定是要使用第二種方式的,為了統(tǒng)一,只介紹第二種方式。
步驟
1、創(chuàng)建配置文件db.properties
無(wú)論是eclipse還是myeclipse,在工程下右鍵->new->file,以properties為后綴名就好了。
配置文件內(nèi)容:
#連接數(shù)據(jù)庫(kù)的url,如果主機(jī)地址是localhost,端口是3306也可以寫(xiě)成url=jdbc:mysql:///databasenameurl=jdbc:mysql://localhost:3306/databasename#用戶名user=root#密碼password=root#MySQL數(shù)據(jù)庫(kù)加載驅(qū)動(dòng)driverClass=com.mysql.jdbc.Driver
2、定義一個(gè)使用jdbc連接數(shù)據(jù)庫(kù)的工具類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)代碼塊中就行,因?yàn)橹恍枰虞d一次就可以了 static{ try{ Properties props = new Properties(); //使用類路徑加載的方式讀取配置文件 //讀取的文件路徑要以“/”開(kāi)頭,因?yàn)槿绻褂?ldquo;.”的話,當(dāng)部署到服務(wù)器上之后就找不到文件了,使用“/”開(kāi)頭會(huì)直接定位到工程的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"); //注冊(cè)驅(qū)動(dòng)程序 Class.forName(driverClass); }catch(Exception e){ e.printStackTrace(); System.out.println("驅(qū)動(dòng)程序注冊(cè)失?。。。?quot;); } } //獲取連接對(duì)象Connection public static Connection getConnection(){ try{ return DriverManager.getConnection(url,user,password); }catch(SQLException e){ e.printStackTrace(); //跑出運(yùn)行時(shí)異常 throw new RuntimeException(); } } //關(guān)閉連接的方法,后打開(kāi)的先關(guān)閉 public static void close(Connection conn,Statement stmt,ResultSet rs){ //關(guān)閉ResultSet對(duì)象 if(rs != null){ try{ //關(guān)閉rs,設(shè)置rs=null,因?yàn)閖ava會(huì)優(yōu)先回收值為null的變量 rs.close(); rs = null; }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(); } } //關(guān)閉Statement對(duì)象,因?yàn)镻repareStatement和CallableStatement都是Statement的子接口,所以這里只需要有關(guān)閉Statement對(duì)象的方法就可以了 if(stmt != null){ try{ stmt.close(); stmt = null; }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(); } } //關(guān)閉Connection對(duì)象 if(conn != null){ try{ conn.close(); conn = null; }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(); } } }}
可以聊任何java問(wèn)題,JavaSE、JavaEE
工具類已經(jīng)實(shí)現(xiàn)了,可以直接考到項(xiàng)目里使用,但是有一點(diǎn)要注意,就是這個(gè)類文件中沒(méi)有導(dǎo)入支持的類,大家也可以看到在類的頭部沒(méi)有package
和import
,這個(gè)需要自己手動(dòng)添加上,導(dǎo)入類的快捷鍵是Ctrl+Shift+O,導(dǎo)包的時(shí)候不要導(dǎo)錯(cuò)了;別忘了引入MySQL的支持jar包mysql-connector-java-5.1.7-bin.jar
附:mysql-connector-java-5.1.7-bin.jar可點(diǎn)擊此處本站下載。
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選