I am trying to connect to a SQL Server 2008 R2 instance which is using sql auth. No exception is raised (I'm catching SqlException), and my code is as follows:
SQLServerDataSource ds = new SQLServerDataSource();
ds.setUser(dbUserID);
ds.setPassword(Password);
ds.setServerName(DBServer);
ds.setPortNumber(1433);
ds.setDatabaseName(dbName);
con = (SQLServerConnect开发者_开发问答ion) ds.getConnection();
Statement statement = con.createStatement();
resultSet = statement.executeQuery(SQL);
All the parameters (username, password, etc) are 100% correct. The database is running etc. The query is a simple select * from a table which exists. There are no null objects after they're used, connection object is setup etc, but the resultset has 0 rows.
Any ideas what I'm doing wrong? I'm using Microsoft SQL Server JDBC Driver 3.0.
Thanks
Making some assumptions here:
You are using SQL Auth and you can connect using the dbuserid and password parameters from either the command line or even SQL Management Studio.
You can telnet into the server on 1433, i.e. make sure there is not firewall or port forwarding issues. Use telnet 123.123.123.123 1433. You should make a connection right away. If not, you need to fix that.
I took you code and just ran it against one of my SQL 2008 databases using JDBC 3 (excuse the quick and dirty code).
import com.microsoft.sqlserver.jdbc.SQLServerConnection;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import java.sql.ResultSet;
import java.sql.Statement;
public class testdelete
{
private static void displayRow(String title, ResultSet rs) {
try {
System.out.println(title);
System.out.println("Sales ID - Pkts Sold");
while (rs.next()) {
System.out.println(rs.getString("SALES_ID") + " : " + rs.getString("Pkts"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
System.out.println("testing...");
String dbUserID = "sa";
String Password = "MYPWD";
String DBServer = "123.123.123.123";
String dbName = "MYDB";
SQLServerConnection con;
ResultSet rs;
String SQL = "select top 10 * from Sales";
SQLServerDataSource ds = new SQLServerDataSource();
ds.setUser(dbUserID);
ds.setPassword(Password);
ds.setServerName(DBServer);
ds.setPortNumber(1433);
ds.setDatabaseName(dbName);
try
{
con = (SQLServerConnection) ds.getConnection();
Statement statement = con.createStatement();
rs = statement.executeQuery(SQL);
displayRow("SALES", rs);
} catch (Exception e)
{
e.printStackTrace();
}
}
}
精彩评论