I am trying to connect my Java code to a Microsoft SQL Server 2008 R2 Express database. I have downloaded the Microsoft SQL Server JDBC Driver 3.0 and added the sqljdbc4.jar to my classpath. I am using Netbeans and have included the sqljdbc4.jar in my project also.
I created a database in the SQL Server Management Studio called TestDB1 and added some columns and values that I will use for testing. I changed from Windows Authentication Mode by right clicking on the server JACOB=PC\SQLEXPRESS->Properties->Secuity and changing from Windows Authentication Mode to SQL Server and Windows Authentication Mode.
I then created a new login by right clicking on the Login folder in the window explorer under JACOB-PC/SQLEXPRESS->Secuity Folder->Logins Folder and added a new login. I gave it the name jhaip2, switched to SQL Server authentication and the set the password to jacob. Enforce password policy and enforce password expiration are unchecked. The default database is set to TestDB1. Then under TestDB1->Secuity->Users->jhaip2->Database role membership I set jhaip2 to db_owner (I couldn't log in to the database in the management studio without doing this, probably not the right thing to do?). I then restarted the server.
Now for my java code, it is basically a direct copy of the JDBC Driver 3.0 Sample code except without windows authentication.
package databasetest1;
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB1;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver okay");
con = DriverManager.getConnection(connectionUrl,"jhaip2","jacob");
System.out.println("Connection Made");
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
When I run, it prints out "Driver okay" so I am assuming my driver is set up correctly. Then it prints the error:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'jhaip2'.
It does not matter what username I use, it always fails. I have a feeling I am setting up the user wrong. If anyone could give me some help on how to properly set up a user or any guidance in how to simply connect to a SQL Server database in Java, I would appreciate it.