- 下載對應版本的JDBC Driver,解壓并安裝
- 將C:\Program Files\Microsoft JDBC Driver 6.4 for SQL Server\sqljdbc_6.4\chs\auth\根據(jù)系統(tǒng)選擇x64或x86\sqljdbc_auth.dll復制到系統(tǒng)目錄C:\Windows\System32
-
在SQL Server配置管理器中啟用TCP/IP協(xié)議,并將IP地址->IPAII->TCP動態(tài)端口修改為1433,重新啟動SQL Server服務
*1433是根據(jù)Eclipse報錯得知
*小插曲,系統(tǒng)更新后發(fā)現(xiàn)配置管理器找不到了,實際上文件在C:\Windows\System32\SQLServerManager14.msc,重新把快捷方式加入開始菜單即可 - 在Java Project中需要加入相應的jar文件。步驟:package explorer中右擊工程->Build Path->Add External Archives
代碼:
需要特別注意Windows身份驗證的連接URL寫法,官方文檔上有
//Use the JDBC driver
import java.sql.*;
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
public class Test {
// Connect to your database.
// Replace server name, user name, and password with your credentials
public static void main(String[] args) {
String connectionString = "jdbc:sqlserver://localhost;" + "integratedSecurity=true;" + "databaseName=test;";
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT sname from student";
statement = connection.createStatement();
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next())
{
System.out.println(resultSet.getString(1));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (resultSet != null) try { resultSet.close(); } catch(Exception e) {}
if (statement != null) try { statement.close(); } catch(Exception e) {}
if (connection != null) try { connection.close(); } catch(Exception e) {}
}
}