標籤:
首先下載JDBC::http://www.microsoft.com/zh-cn/download/details.aspx?id=21599
下載 完成後,是個exe檔案,點擊運行,會提示你選擇解壓目錄.
解壓完成後,進入 <你解壓到得目錄>\sqljdbc_3.0\chs,裡邊有兩個我們需要的東東
一個是:sqljdbc.jar,另外一個是sqljdbc4.jar
這裡使用sqljdbc4.jar
首先配置sa身分識別驗證:
由於安裝sqlServer2008時是以windows身分識別驗證安裝的,並沒有為sqlServer2008添加sqlServer身份使用者,因此首先添加使用者:
開啟Microsoft SQL Server Managerment Studio並以windows驗證方式登入,左側的物件總管->安全性->登入名稱,右擊sa->屬性,為sa使用者添加密碼,選擇sqlServer身分識別驗證,在"狀態"選項中授予串連到資料庫和登入啟用.右擊物件總管的根節點,選擇屬性->安全性->sqlServer和windows身分識別驗證模式,這樣就為sql server 2008建立了以sql server身分識別驗證的使用者sa.
在java代碼中用兩種方式串連sqlserver2008資料庫,一種是sa身分識別驗證模式,另外一種是混合身分識別驗證模式:
第一種:sa身分識別驗證模式,用下邊java代碼的url
Java代碼 收藏代碼
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
public static void main(String args[]) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;"
+ "databaseName=AdventureWorks;integratedSecurity=true;";
String url = "jdbc:sqlserver://127.0.0.1:1368;databaseName=mydb;user=sa;password=qiaoning";//sa身份串連
String url2 = "jdbc:sqlserver://127.0.0.1:1368;databaseName=mydb;integratedSecurity=true;";//windows整合模式串連
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
System.out.println("begin.");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(url);
System.out.println("end.");
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM aud_t_basis";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
}
if (stmt != null)
try {
stmt.close();
} catch (Exception e) {
}
if (con != null)
try {
con.close();
} catch (Exception e) {
}
}
}
}
第二種:混合身分識別驗證模式,用上邊java代碼的url2.
在整合模式下需要如下操作:
找到你剛才的解壓目錄:進入sqljdbc_3.0\chs\auth\x64,我的是64位系統,如果是32位就x86,將一個名為sqljdbc_auth.dll的檔案拷貝到:C:\Windows\System32下,就好了
最後就是sqlserver2008用的是動態連接埠,需要你配置一下:
開啟組態工具->SQLServer組態管理員->SQLServer網路設定->MSSQLSERVER的協議->TCP/IP啟用,把TCP動態連接埠中的0都刪掉,留空;然後把列表拉到最下邊(IPALL),配置一個固定連接埠,以後你串連資料庫就用這個連接埠就可以了:如
轉:Java串連SqlServer2008資料庫