SQL Server jdbc连接

yat*_*nbc 4 java sql-server-2005 jdbc

我在windows身份验证中在localhost上运行此代码片段但是出现了以下错误,但我已经在我的类路径中添加了sqljdbc4 jar,并且在从eclipse运行时我也在构建路径中添加了jar

import java.io.*;
import java.sql.*;
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

class  Cms_truncate
{
    public static void main(String[] args) 
    {
         Calendar cal = new GregorianCalendar();

         //String name="cmscim";
                 Connection conn = null;

         String url = "jdbc:sqlserver://localhost\SQLEXPRESS;databasename=yatin";
         String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
         String userName = ""; 
         String password = "";
         Statement stmt;
         try
         {

         Class.forName(driver);//.newInstance();
         conn = DriverManager.getConnection(url,userName,password);
         String query = "truncate table cim";
         stmt = conn.createStatement();
         int flag = stmt.executeUpdate(query);
         System.out.println("flag = "+flag); 
         conn.close();
        System.out.println("");
         } catch (Exception e) {
         e.printStackTrace();
         }

    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
    at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
    at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at Cms_truncate.main(Cms_truncate.java:28)
Run Code Online (Sandbox Code Playgroud)

请帮帮我.

Pau*_*mer 10

此错误不会说"身份验证错误",它会因"连接被拒绝"而显示"连接错误".这意味着您需要指定正确的端口号.您需要检查SQL Server配置并更新连接字符串.

根据MSDN文档,连接字符串应如下所示:

jdbc:sqlserver://localhost:<insert_proper_port_here>\SQLEXPRESS;databasename=yatin
Run Code Online (Sandbox Code Playgroud)

您没有提供用户名或密码,一旦您弄清楚了端口号,您可能需要这样做.有关详细信息,请参阅参考文档.