用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身份验证)_第1张图片

    用JDBC连接SQL Server(Windows身份验证)_第2张图片

    用JDBC连接SQL Server(Windows身份验证)_第3张图片

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

  4. 在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) {}   
            }  
        }  

你可能感兴趣的:(用JDBC连接SQL Server(Windows身份验证))