用JDBC连接SQL Server(Windows身份验证)

  1. 下载对应版本的JDBC Driver,解压并安装
  2. 将C:\Program Files\Microsoft JDBC Driver 6.4 for SQL Server\sqljdbc_6.4\chs\auth\根据系统选择x64或x86\sqljdbc_auth.dll复制到系统目录C:\Windows\System32
  3. 在SQL Server配置管理器中启用TCP/IP协议,并将IP地址->IPAII->TCP动态端口修改为1433,重新启动SQL Server服务

    《用JDBC连接SQL Server(Windows身份验证)》
    《用JDBC连接SQL Server(Windows身份验证)》
    《用JDBC连接SQL Server(Windows身份验证)》

    *1433是根据Eclipse报错得知
    *小插曲,系统更新后发现配置管理器找不到了,实际上文件在C:\Windows\System32\SQLServerManager14.msc,重新把快捷方式加入开始菜单即可

  4. 在Java Project中需要加入相应的jar文件,貌似是作为动态链接库使用的,我不是很懂这些。步骤:package explorer中右击工程->Build Path->Add External Archives
    *一开始设置了环境变量CLASSPATH,后来看到说不需要,经测试确实不需要

代码:

需要特别注意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 (connection != null) try { connection.close(); } catch(Exception e) {} 
                if (statement != null) try { statement.close(); } catch(Exception e) {}  
                if (connection != null) try { connection.close(); } catch(Exception e) {}   
            }  
        }  
    原文作者:blackOak
    原文地址: https://www.jianshu.com/p/ef06c0965192
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞