首先下載JDBC Driver for SQL Server驅動程序,地址
https://docs.microsoft.com/zh-cn/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server
配置驅動程序包
解壓包sqljdbc_6.2.2.0_chs.tar.gz,將驅動包放到ext下面
java連接測試:
package testConnectSqlserver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestConnectSqlServer {
public static void main(String[] args) {
// 測試連接sqlserver數據
//MultiSubnetFailover=true表示支持故障轉移群集
//ApplicationIntent=ReadOnly表示連接讀取意向的數據庫(一般指副本)
String connectionUrl = "jdbc:sqlserver://122.50.66.188:1433;databaseName=testdb;user=sa;password=123456;ApplicationIntent=ReadOnly;MultiSubnetFailover=true";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.加载驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("加载驱动成功!");
}catch(Exception e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
}
try {
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String sql = "SELECT * FROM Table_1";
sql="SELECT [Id],[WebName],[WebUrl],[WebLogoUrl],[CreateTime] FROM [dbo].[sys_Link]";
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(1) + " " + rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)+" "+rs.getString(5));
}
}
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) {
}
}
}
}