简体   繁体   中英

Connecting SQL Server 2008 to Java: Login failed for user error

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.

  1. run this query by selecting your database

     CREATE LOGIN aaron792 WITH PASSWORD='12345' USE BudgetAuthorization CREATE USER aaron792

    i use aaron792 you should use yours

  2. In sql server management studio go to object explorer and right click on (local)(sql server xxx) then go to properties it will open server properties and then go to security and change server authentication mode from windows only to sql server or windows (2nd option)

     USE [master] GO EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\\Microsoft\\MSSQLServer\\MSSQLServer', N'LoginMode', REG_DWORD, 2 GO
  3. in server properties , go to permissions and select newly created user from Logins or rules list then below it check all options for grant in explicit rule

  4. open SQL server configuration manager and -> sql server services at top row SQL server right click and open properties then change built in account to Local System

then restart every thing and make sure it is running. then try your code

I know this has already being answered but would like to give a little twist to it without having to reinstall the whole SQLSERVER RDBMS. The concept is to change the properties of the sqlserver instance you are trying to connect to.

  1. Step one . Open SQL Management Studio and select the sql server instance from the object explorer.

    • Right click on the instance and select properties from the popup menu which will open a Server Property Window.
    • select Security option which is located at the right side of the page. Then change server authentication from Windows Authentication mode to SQL SERVER and Windows Authentication mode (mixed mode) .
    • Select Permissions option afterwards. Then with Permissions selected, select the Login Account you would like to grant permission to. (Login Account should be created before this, check this tutorial out http://www.blackthornesw.com/robo/projects/blackthornepro/HOWTO_-_Creating_a_SQL_Server_Database_Login_Account.htm . The edition might be different from what you have but the concept or workflow remains the same.). Under the permissions, select the Explicit tab, and under Grant , select all the options.
    • Click OK.
  2. Step Two : to configure the RDBMS to use the internally created Login Accounts. Therefore:

    • Open/Start SQLSERVER configuration Manager .
    • Select SQL SERVER Services from the left pane.
    • With that selected, move to the right pane and right click on SQL Server (MSSQLSERVER) option and then select properties from the popup menu.
    • SQL Server (MSSQLSERVER) properties window appears, make sure Log On tab is selected, then select the radio button named Built-in Account under Log on as: Option. Then select from the combo box, Local System .
    • Click OK. By clicking on ok, you will be asked to restart the instance, go ahead to restart it. If restart is not asked, then move to step three below.
  3. Step Three : to restart the SQLSERVER RDBMS.

    • Go to Control Panel > Administrative Tools > Component Services .
    • Select Services from the left pane
    • Then select SQL Server (MSSQLSERVER) from the right pane, the click restart which is just a little to the top right side.

When I looked in the SQL Server log files, it was saying that I couldn't log in because SQL Server was in Windows Authentication mode, even though in the program it was set to Mixed Authentication Mode.

When installing, I had set it up in Windows Authentication mode but changing the settings in the program would not change it from Windows Authentication mode.

I removed SQL Server 2008 and all related programs from my computer and installed a fresh copy, this time with SQL Server Authentication. Everything works correctly now. I don't know why SQL Server had a problem with changing the authentication mode, but it works now so I am happy.

Would this other question possibly be the same issue: MS SQL Server 2005 Express x86 - its port is unreachable - help .

You have to make sure that SQL Server is listening on the correct port before you can connect via a TCP connection using JDBC.

I ran into the same issue. Thank you, jhaip, for pointing me to the right direction: SQL Server was in Windows Authentication mode.

I'd like only to add that it is not necessary to reinstall the SQL server and all related programs. What's just needed is to change authentication mode. See this answer for more details: An attempt to login using SQL authentication failed

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM