Freigeben über


如何使用JDBC驱动来测试SQL Server连接

大家可能都知道如何使用ODBC, OLEDB或者SQL Native Client这些驱动来测试SQL Server的连接。那么如何使用JDBC驱动来测试SQL Server连接呢?

今天我们提供一个使用JDBC驱动去连接SQL Server的具体步骤

1 安装

Microsoft SQL Server JDBC驱动3.0(运行在JDK5.0版本及以上)             

https://www.microsoft.com/download/en/details.aspx?id=21599

下载JDK7.0

https://www.oracle.com/technetwork/java/javase/downloads/index.html   2 设置系统环境变量(CLASSPATH)

2 设置系统环境变量(CLASSPATH)

系统环境变量 (注意:设置完类路径之后记得重启电脑。)

变量名:  CLASSPATH

值:  C:\Program Files\Microsoft SQL Server 2005 JDBC Driver\sqljdbc_1.0\enu\sqljdbc.jar

 

3 用Java样例代码测试连接(接下来两个例子都是使用SQL 2005 JDBC驱动)

1) 将本文的附录中脚本分别保存成以下两个java文件

 Connect.java:  该代码尝试连接数据库,显示数据库名,版本信息,还有可用的目录。用你服务器的值替换样例代码里的服务器属性。
 testConnect.java:   该代码尝试测试和SQL Server的连接,如果连接成功的话会显示‘连接成功’。替换样例代码里的相关连接属性,如服务器名等。

请参考MSDN文档来构造连接字符串:https://msdn.microsoft.com/en-us/library/ms378428(SQL.90).aspx

2) 把附件中的样例java代码移到java.exe和javac.exe所在的目录,默认的目录路径是 C:\Program Files\Java\jdk1.7.0\bin

3) 编译样例java代码,类似:javac Connect.java    注意:“Connect.java” 大小写敏感 。

4) 运行它  :java Connet     注意:“Connect” 大小写敏感 。

 

4 附加信息

1)     SQL Server 2000 JDBC驱动和SQL Server 2005 JDBC驱动的类名不同。

         * SQL Server 2000 JDBC驱动类名:"com.microsoft.jdbc.sqlserver.SQLServerDriver"

         * SQL Server 2005 JDBC驱动类名:"com.microsoft.sqlserver.jdbc.SQLServerDriver"

        另外,SQL Server 2005 JDBC驱动的URL前缀和SQL Server 2000 JDBC驱动的也不一样。

         * SQL Server 2000 使用的URL 前缀:  "jdbc:microsoft:sqlserver://"

         * SQL Server 2005 使用的URL 前缀:  "jdbc:sqlserver://"

  2)     MSDN上的JDBC信息:https://msdn.microsoft.com/en-us/sqlserver/aa937724

 

 

===========================附录===========================

testConnection.java script content

import java.*;
import java.sql.*;
import java.util.*;
import java.text.*;
import java.sql.SQLException;
import java.util.logging.FileHandler;
import java.io.IOException;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.LogRecord;
import java.util.logging.SimpleFormatter;
import java.util.Date;

class testConnection
{
  public static void main (String[] args) {
    try
    {
      // Step 1: Load the JDBC driver.
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      // Step 2: Establish the connection to the database.

      String connectionUrl = "jdbc:sqlserver://localhost;databaseName=AdventureWorks;user=sa;password=sa";
      Date strtime = new Date();
      System.out.println("Start Time: " + strtime);
      Connection con = DriverManager.getConnection(connectionUrl);
      Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      logger.setLevel(Level.ALL);
      FileHandler fh = new FileHandler("%t/java.log");
      Date endtime = new Date();       
      System.out.println("End Time is: " + endtime);
      logger.info("Connected.");
      System.out.println("connected");
  
    }
    catch (Exception e)
    {
      System.err.println("Got an exception! ");
      e.printStackTrace();
      System.err.println(e.getMessage());
    }
  }
}

 

Connect.java script content

import java.*;
public class Connect{
     private java.sql.Connection  con = null;
     private final String url = "jdbc:sqlserver://";
     private final String serverName= "localhost";
     private final String portNumber = "1433";
     private final String databaseName= "northwind";
     private final String userName = "sa";
     private final String password = "sa";
     // Informs the driver to use server a side-cursor,
     // which permits more than one active statement
     // on a connection.
     private final String selectMethod = "cursor";
    
     // Constructor
     public Connect(){}
    
     private String getConnectionUrl(){
          return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
     }
    
     private java.sql.Connection getConnection(){
          try{
               Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
               con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
               if(con!=null) System.out.println("Connection Successful!");
          }catch(Exception e){
               e.printStackTrace();
               System.out.println("Error Trace in getConnection() : " + e.getMessage());
         }
          return con;
      }

     /*
          Display the driver properties, database details
     */

     public void displayDbProperties(){
          java.sql.DatabaseMetaData dm = null;
          java.sql.ResultSet rs = null;
          try{
               con= this.getConnection();
               if(con!=null){
                    dm = con.getMetaData();
                    System.out.println("Driver Information");
                    System.out.println("\tDriver Name: "+ dm.getDriverName());
                    System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
                    System.out.println("\nDatabase Information ");
                    System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
                    System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
                    System.out.println("Avalilable Catalogs ");
                    rs = dm.getCatalogs();
                    while(rs.next()){
                         System.out.println("\tcatalog: "+ rs.getString(1));
                    }
                    rs.close();
                    rs = null;
                    closeConnection();
               }else System.out.println("Error: No active Connection");
          }catch(Exception e){
               e.printStackTrace();
          }
          dm=null;
     }    
    
     private void closeConnection(){
          try{
               if(con!=null)
                    con.close();
               con=null;
          }catch(Exception e){
               e.printStackTrace();
          }
     }
     public static void main(String[] args) throws Exception
       {
          Connect myDbTest = new Connect();
          myDbTest.displayDbProperties();
       }
}