java - 使用 JDBC 连接 SQL Server 2008 R2 时出错

标签 java sql-server-2008

我正在使用 Java 连接 Microsoft SQL Server 2008 R2sqljdbc4.jar,但初始连接出现问题。运行后,浏览器中只显示3。

这是我的代码:

import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class Database { 
static Connection con = null;
public static int dbConnect() {
    int x = 3;
    try {
        // Establish the connection. 
        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setIntegratedSecurity(true);
        ds.setServerName("172.18.16.10");
        ds.setPortNumber(1433); 
        ds.setDatabaseName("my-database");
        ds.setUser("my-user");
        ds.setPassword("my-pass");
        con = ds.getConnection();
        x = 5;
        if (con != null) {
            x = 1;
        }else{
            x = 0;
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());  
    }
    return x;   
}}

这是我收到的错误:

Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. ClientConnectionId:af711e9c-941f-4535-9ccb-b6ef31a42fdf

关于我的问题的旧问题对我没有帮助。我将 sqljdbc-auth.jar 添加到 /java/bin 中,并将 path 也添加到 /java/lib

最佳答案

我添加 sqljdbc.jar 并导入它:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.*;

我在全局和静态中定义了所有需要的变量:

private static SQLServerDataSource ds = null;
private static Connection con = null;

并定义连接方法:

    public static boolean getConnection() {
    try {
        System.out.println(ServerName);
        ds = new SQLServerDataSource();
        ds.setServerName(ServerName);
        ds.setPortNumber(1433);
        ds.setDatabaseName(DatabaseName);
        ds.setUser(UserName);
        ds.setPassword(Password);
        con = ds.getConnection();
        if (con != null) {
            System.out.println("Success");
        }
        stmt = con.createStatement();
        return true;
    } // Handle any errors that may have occurred.
    catch (Exception e) {
        System.out.println(e.getMessage());
        return false;
    }
}

关于java - 使用 JDBC 连接 SQL Server 2008 R2 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31003746/

相关文章:

java - 如何使用 ObjectWeb2 ASM 引导接口(interface)方法引用

java - Spring JPA 属性表达式通过列表中项目的交集查找

mysql - 为什么 "schema"在 MySQL 和 SQL Server 中不同?

sql - 为什么在获取批量数据(没有空间)时SQL查询执行时间过长?

sql - 计算一列中另一列中有多个值的不同记录

java - Spring Framework 3.2.5 - 对 POST API 输出的响应正文进行解码的问题

java - 更改运行 netbeans 的 Java 平台

java - 获取相似对象属性的通用方法

c# - SQL Server 计算列如何在 EntityFramework 中工作?

sql-server - DATEDIFF 不正确的结果