如果是 jdk7 和 jdk7 以前的版本,用 jdbc.jar
如果是 JDK8,用 jdbc4.jar 下载地址:https://mvnrepository.com/artifact/com.microsoft.sqlserver.jdbc/sqljdbc4/4.0
把jdbc4.jar 复制到java 目录 D:\Program Files\Java\jdk1.8.0_301\jre\lib\ext\jdbc4.jar
然后启动应用类测试
- public class xxxxx {
- public static void main(String[] args)
- {
- String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
- String dbURL="jdbc:sqlserver://192.168.2.222:1433;DatabaseName=bylsn";
- String userName="mg";
- String userPwd="mg";
- try
- {
- Class.forName(driverName);
- Connection dbConn= DriverManager.getConnection(dbURL,userName,userPwd);
- Statement stmt = dbConn.createStatement();
- String sql ="SELECT * FROM [dbo].[xxxx] WHERE name = 'xxx'";
- ResultSet rs = stmt.executeQuery(sql);
- while(rs.next()){ //循环遍历查询结果集
-
- System.out.println(rs.getString("xxxx"));
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- System.out.print("fail!");
- }
- }
-
- }
如果链接报错,com.microsoft.sqlserver.jdbc.SQLServerException: 驱动程序无法通过使用安全套接字层(SSL)加密与 SQL Server 建立安全连接。错误:“The server selected protocol version TLS10 is not accepted by client preferences [TLS12]”。
需要改下面这个文件几个禁用字符去掉
D:\Program Files\Java\jdk1.8.0_301\jre\lib\security\java.security
1.jdk.tls.legacyAlgorithms
jdk.tls.legacyAlgorithms=SSLv3, RC4, DES, MD5withRSA, \
DH keySize < 1024, EC keySize < 224, anon, NULL, \
include jdk.disabled.nameCurves
2.jdk.certpath.disabledAlgorithms中改为:
jdk.certpath.disabledAlgorithms=MD2, MD5, SHA1 jdkCA & usage TLSServer, \
RSA keySize < 1024, DSA keySize < 1024, EC keySize < 224, \
include jdk.disabled.namedCurves