本文實例講述了Java使用jdbc連接MySQL數據庫的方法。分享給大家供大家參考,具體如下:
使用jdbc連接數據庫:
可以直接在方法中定義url、user、psd等信息,也可以讀取配置文件,但是在web項目中肯定是要使用第二種方式的,為了統一,只介紹第二種方式。
步驟
1、創建配置文件db.properties
無論是eclipse還是myeclipse,在工程下右鍵->new->file,以properties為后綴名就好了。
配置文件內容:
#連接數據庫的url,如果主機地址是localhost,端口是3306也可以寫成url=jdbc:mysql:///databasenameurl=jdbc:mysql://localhost:3306/databasename#用戶名user=root#密碼password=root#MySQL數據庫加載驅動driverClass=com.mysql.jdbc.Driver
2、定義一個使用jdbc連接數據庫的工具類JdbcUtil.java
工具類內容:
public class JdbcUtil{ //定義全局變量 private static String url = null; private static String user = null; private static String password = null; private static driverClass = null; //讀取配置文件內容,放在靜態代碼塊中就行,因為只需要加載一次就可以了 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"); //注冊驅動程序 Class.forName(driverClass); }catch(Exception e){ e.printStackTrace(); System.out.println("驅動程序注冊失敗?。?!"); } } //獲取連接對象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會優先回收值為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
工具類已經實現了,可以直接考到項目里使用,但是有一點要注意,就是這個類文件中沒有導入支持的類,大家也可以看到在類的頭部沒有package
和import
,這個需要自己手動添加上,導入類的快捷鍵是Ctrl+Shift+O,導包的時候不要導錯了;別忘了引入MySQL的支持jar包mysql-connector-java-5.1.7-bin.jar
附:mysql-connector-java-5.1.7-bin.jar可點擊此處本站下載。
希望本文所述對大家java程序設計有所幫助。
新聞熱點
疑難解答
圖片精選