標籤:
1 package com.cps.rom.utils; 2 3 /******************************************************************************* 4 *使用Java純驅動串連到MS SQL Server 2000資料庫的測試程式 5 *劉宇 6 *日期:2005-11-06 7 ******************************************************************************/ 8 9 /*******************************************************************************10 *準備工作:11 *1、要使用Java純驅動串連SQL Server 2000資料庫,必須先獲得由資料庫廠商提供的驅動12 * 程式。13 *2、將DBDriver目錄中的jdbcSQLServer目錄拷貝到本地磁碟上。14 *3、在環境變數中設定classpath,指定好驅動程式的路徑。驅動程式共有三個.jar檔案,15 * 三個檔案的路徑都必須指定。16 *4、在編寫Java程式的開發環境(如:JCreator等)中也應指定上述檔案的路徑。17 ******************************************************************************/18 //要串連資料庫,則必須包含java.sql包19 20 public class test {21 public static void main(String args[]) {22 System.out.println("正在串連資料庫,請稍候...");23 try {24 // 第一步:註冊JDBC驅動程式25 /*26 * 如果是通過純JAVA驅動的方式串連SQL Server,就固定使用如下字串:27 * "com.microsoft.jdbc.sqlserver.SQLServerDriver" 不可以更改28 */29 // forName()方法有可能拋出ClassNotFoundException異常,必須捕獲30 // java.lang.Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");31 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");32 // 第二步:串連到資料庫33 /*34 * 設定連接字串,應採用如下格式:35 * "jdbc:microsoft:sqlserver://伺服器名或IP地址:連接埠號碼(預設1433);databaseName=資料庫名"36 */37 // 這裡串連到SQL Server的pubs資料庫38 // String strCon =39 // "jdbc:microsoft:sqlserver://localhost:1433;databaseName=DB_WuLiu";40 41 String strCon = "jdbc:sqlserver://localhost:1433;databaseName=DB_WuLiu";42 43 String strUserName = "sa"; // 資料庫的使用者名稱稱44 String strPWD = "123"; // 資料庫的密碼45 // 建立資料庫連接46 // getConnection()方法是DriverManager類的靜態方法47 // getConnection()方法有可能拋出SQLException異常,必須捕獲48 java.sql.Connection con = java.sql.DriverManager.getConnection(strCon, strUserName, strPWD);49 System.out.println("已順利串連到資料庫。");50 51 // 第三步:利用上面建立的串連建立語句物件控點52 java.sql.Statement sta = con.createStatement();53 sta.setQueryTimeout(30); // 設定作業延時為30秒54 55 // 接下來,利用上面建立的語句物件控點,對資料庫進行操作56 String strQuery = "SELECT * FROM db_Customer"; // 查詢語句57 java.sql.ResultSet rs = sta.executeQuery(strQuery); // 執行查詢語句,返回記錄集58 int count = 0; // 計數器59 System.out.println("查詢到的資料:");60 while (rs.next()) {61 String strFirstName = rs.getString("Name"); // 獲得指定欄位的資料62 String strLastName = rs.getString("Email");63 count++; // 計數器計數64 System.out.println(strFirstName + "." + strLastName); // 列印查詢出來的資料65 }66 System.out.println("共查詢到" + count + "行資料。"); // 統計查詢出多少條資料67 68 // 對資料庫操作完畢後,關閉所有被開啟的資源69 rs.close(); // 關閉記錄集70 sta.close(); // 關閉語句物件控點71 con.close(); // 關閉串連72 System.out.println("資料庫已關閉。");73 }74 // 捕獲異常並進行處理75 catch (java.lang.ClassNotFoundException cnfe) {76 System.out.println(cnfe.getMessage());77 } catch (java.sql.SQLException se) {78 System.out.println(se.getMessage());79 }80 }81 }
java串連sql server