總結一下,連接SQL Server數據庫需要以下幾個步驟:
1. 導入驅動Jar包:sqljdbc.jar
2. 加載並注冊驅動程序
3. 設置連接路徑
4. 加載並注冊驅動
5. 連接數據庫
6. 操作數據庫
7. 關閉連接
代碼如下:
******************連接數據庫*******************
1 package zj6_Test; 2 import java.sql.*; 3 public class Zj6_3 { 4 /** 5 * 使用Statement接口實現對數據庫的增刪改操作 6 */ 7 private static final String driver= 8 "com.microsoft.sqlserver.jdbc.SQLServerDriver";//加載並注冊驅動程序 9 private static final String url= 10 "jdbc:sqlserver://localhost:1433;DataBaseName=Bank";//設置連接路徑 11 public static void main(String[] args) { 12 Connection con=null;//建立連接池 13 Statement sta=null; 14 try { 15 Class.forName(driver);//加載並注冊驅動 16 con=DriverManager.getConnection(url, "sa", "sa");//連接數據庫 17 // 向數據庫Bank表中添加數據 18 sta=con.createStatement();//通過createStatement()方法得到Statement接口的引用指向的對象 19 sta.execute("insert into ACCOUNT values('曹操','420106198205188777','2011-07-07')"); 20 sta.close(); //關閉Ststement對象 21 // //修改表中ACCOUNT_ID為7的數據 22 // String ACCOUNT_NAME="曹植"; 23 // String CODE="420683199203212111"; 24 // String OPEN_TIME="2011-07-10"; 25 // sta=con.createStatement(); 26 // String updatesql="update ACCOUNT set ACCOUNT_NAME='"+ACCOUNT_NAME+"',CODE='"+CODE+"',OPEN_TIME='"+OPEN_TIME+"'where ACCOUNT_ID="+7 ; 27 // 28 // sta.execute(updatesql); 29 // sta.close(); 30 // //刪除ACCOUNT表中ACCOUNT_ID=7的記錄 31 // sta=con.createStatement(); 32 // String delsql="delete from ACCOUNT where ACCOUNT_ID="+7; 33 // sta.executeUpdate(delsql); 34 // sta.close(); 35 // con.close(); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40 }
運行結果:
當然,實際應用中,為了體現java封裝的特性,往往會把重復使用的方法封裝到一個類中,每次直接拿來用就可以了。
下面給一個封裝的類:
1 package zj6_Test; 2 import java.sql.*; 3 public class DBManager { 4 /** 5 * 建立專門的自定義類,來實現建立連接、關閉對象和關閉連接 6 */ 7 private static final String driver= 8 "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 9 private static final String url= 10 "jdbc:sqlserver://localhost:1433;DataBaseName=Bank"; 11 private static final String user="sa"; 12 private static final String pwd="sa"; 13 private static Connection con=null;//建立連接池對象 14 //建立與數據庫的連接 15 public static Connection getCon(){ 16 try { 17 Class.forName(driver); 18 con=DriverManager.getConnection(url,user,pwd); 19 } catch (Exception e) { 20 21 e.printStackTrace(); 22 } 23 return con; 24 } 25 //關閉Connection 26 public static void closeCon(Connection con){ 27 try { 28 if(con!=null){ 29 con.close(); 30 } 31 } catch (SQLException e) { 32 e.printStackTrace(); 33 } 34 } 35 //關閉ResultSet 36 public static void closeResultSet(ResultSet rst){ 37 try { 38 if(rst!=null){ 39 rst.close(); 40 rst=null; 41 } 42 } catch (Exception e) { 43 e.printStackTrace(); 44 } 45 } 46 //關閉Statement 47 public static void closeStatement(PreparedStatement pst){ 48 try { 49 if(pst!=null){ 50 pst.close(); 51 pst=null; 52 } 53 } catch (Exception e) { 54 e.printStackTrace(); 55 } 56 } 57 }
能力有限,有些地方地方說法不夠專業,還望批評指正!