我正在使用 Java 连接 Microsoft SQL Server 2008 R2 和 sqljdbc4.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/