用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服务





    *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) {}   
            }  
        }  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,957评论 19 139
  • 1.先下载Microsoft SQL Server JDBC Driver 3.0,地址: Download Mi...
    禾_禾阅读 3,202评论 1 8
  • 阳光总是很明媚 白云却要遮住蓝天 几时没路 几时相聚
    月独醉阅读 114评论 0 0
  • 果儿上的是一个不入流的大学,虽然大学毕业了,可是工作很不好找。 她一直有一个做记者的梦想,小时候就觉得电视上干练漂...
    西丝轩主阅读 393评论 2 4