I am using Java to connect Microsoft SQL Server 2008 R2 and sqljdbc4.jar
, but there is a problem with the initial connection. After running, 3 is displayed in the browser only.
This is my code:
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;
}}
and this is the error I receive:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. ClientConnectionId:af711e9c-941f-4535-9ccb-b6ef31a42fdf
The older questions about my problem in SO were not helpful for me. I added sqljdbc-auth.jar
into /java/bin
and path
also in /java/lib
I add sqljdbc.jar and import that :
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.*;
I define all need variable in Global ans Static :
private static SQLServerDataSource ds = null;
private static Connection con = null;
and define a method for connect:
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;
}
}
Try doing something like this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
static Connection con = null
public static int dbConnect() {
int x = 3;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://172.18.16.10:1433;databaseName=my-database;user=my-user;password=my-pass;");
x = 5;
if (con != null) {
x = 1;
}else{
x = 0;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return x;
}
}
You will get a proper connection using the above code.
Morever, the driver Name ("com.microsoft.sqlserver.jdbc.SQLServerDriver") and the connection url should always be read from a config file. Try taking the above two things out of your code into a config file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.