java.sql.SQLException: Login failed for user 'admin'

EMM picture EMM · Dec 24, 2014 · Viewed 14k times · Source

Disclaimer: I have never used SQL server before.

I am trying to connect to SQL server Express using java code.

public class Test1 {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        String url = "jdbc:jtds:sqlserver://localhost:1433/POC;instance=MOHITCH-LAPTOP/SQLEXPRESS";
        String user = "admin";
        String password = "admin";
        Connection conn = DriverManager.getConnection(url, user, password);
        Statement st = conn.createStatement ();
            ResultSet rs = st.executeQuery("select * from POC.dbo.poc_table");
            while (rs.next())
            {
                System.out.println(rs.getInt(1) + " " + rs.getString(2));
            }
        }
    }

And I am getting the exception:

Exception in thread "main" java.sql.SQLException: Login failed for user 'admin'.
    at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
    at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2820)
    at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2258)
    at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:603)
    at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:352)
    at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
    at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:185)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at my.java.Test1.main(Test1.java:16)

I also tried logging in using MS SQL server Management Studio 2014. And I successfully did it.

enter image description here

Here is my database structure:

enter image description here

Any help is highly appreciated!!
Thanks

Answer

Ye Win picture Ye Win · Dec 24, 2014

I think you need to modify some configuration in your server.

Please follow the below step and hope this will help you.

1. Open your SQL Server Management Studio.

2. Database server right click and go to properties.

3. Choose Security option and check SQL Server and Windows authentication mode.

4. Enable TCP/IP connection in SQL Configuration Manager.

5. Restart your SQL server service.