Connecting to SQL Server from Java


Almost every time I try to connect to SQL Server from Java I end up hacking something together, like copy-pasting the connection string from an old project; then again, more often than not I end up getting some sort of error and spending quite sometime Googling. So I spent sometime trying to understand the different options and thought I’d put together a few things I have learnt. I’m using eclipse, so the examples are based on that, but I’m sure you could easily find the equivalent if you’re using a different editor.

There seem to be primarily two ways to connect to SQL Server – using Windows Authentication or SQL Authentication (with a username/password). Also, we have two commonly used JDBC Type IV driversMS-JDBC and jTDS. This gives us four combinations and here are the connection strings/settings you need to get things up and running (you may need to adjust the string according to your PC name, SQL Server instance and DB name):

  1. Windows authentication + JDBC
This is the connection string we have to use:
String url ="jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);

For this to work, you’ll need to have sqljdbc driver included in the build path:
image
Note that you need to point to the sqljdbc4.jar (shown below) in ‘Microsoft JDBC Driver 4.0 for SQL Server’ folder. Make sure you have all other files that go along with it as well as simply having only the .jar won’t do.
image
You would think this would be enough, but if you just run it now you’re going to get the following error:

Jan 22, 2012 1:41:43 PM com.microsoft.sqlserver.jdbc.AuthenticationJNI <clinit>
WARNING: Failed to load the sqljdbc_auth.dll cause :- no sqljdbc_auth in java.library.path

So you also need to add the path to sqljdbc_auth.dll as a VM argument:
image
Now at one stage I was having the 3.0 JDBC driver and was getting the same error above and after wasting a decent amount of time found out that SQL Server 2012 requires the JDBC 4.0 driver. So if you are working with SQL Server 2008 you might need 3.0, although I’m guessing 4.0 should be backward compatible.

2.  SQL authentication + JDBC

This is probably the easiest scenario. You need to add sqljdbc4.jar similar to (1), but don’t need the VM arguments. The connection string to use in this case is:

String userName ="username";
String password ="password";

String url ="jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);

Some details related to setting up a new user can be found here.

3.  Windows authentication + jTDS

jTDS uses Windows authentication by default, so this is the connection string we need to use (don’t need to explicitly mention ‘integrated security’).

String url ="jdbc:jtds:sqlserver://MYPC/MYDB;instance=SQLEXPRESS";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(url);

You also need jtds.jar in the Java build path:
image
Now at this point if you just run it you are going to get the following error:
java.sql.SQLException: I/O Error: SSO Failed: Native SSPI library not loaded. Check the java.library.path system property.
Took me a while to figure out how to resolve this, but what you need to do is something a bit similar to (1). Simply have the following as a VM argument:
image

’Path’ above is where your SSO folder is after installing the jTDS driver. Seems like for Windows authentication to work, Java needs to know where this ntlmaauth.dll is.

image

4.  SQL authentication + jTDS

Very similar to case (2). No VM arguments needed, but still need jtds.jar in the build path. Connection string to use is:

String userName ="username";
String password ="password";
String url ="jdbc:jtds:sqlserver://MYPC/MYDB;instance=SQLEXPRESS";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, userName, password);

Once you have the Connection, you can run a query/stored procedure as follows:
Query/UDF
try{           

    PreparedStatement ps = conn.prepareStatement("select * from yourTable/UDF/query");
    /* if UDF, and need to pass params, can do something like:
    ...prepareStatement("select * from UDF('" + UDFinputVal + "')" */

    ResultSet rs = ps.executeQuery();

    while (rs.next()) {

        String relatedConcept = rs.getString(1);
        int shortestDistance = rs.getInt(2);
        float weightedDistance = rs.getFloat(3);

        // do stuff    }  

    rs.close();
    ps.close();            
}
catch (Exception e) {
    e.printStackTrace();
}

Stored procedure
try{           

    // execute SP that requires two string arguments    PreparedStatement ps = conn.prepareStatement("exec storedProcedure ?,?");
    ps.setEscapeProcessing(true);

    ps.setString(1, "str1");
    ps.setString(2, "str2");

    ResultSet rs = ps.executeQuery();

    while (rs.next()) {
        String strVal = rs.getString(1);
        // do stuff    }

    /* If you get multiple results back from you SP, you can iterate through them using:

    ps.getMoreResults();
    rs = ps.getResultSet();

    while (rs.next()) {
        String strVal = rs.getString(1);
        ... 
    }  */

    rs.close();
    ps.close();            
}
catch (Exception e) {
    e.printStackTrace();
}

Keywords: com.microsoft.sqlserver.jdbc.AuthenticationJNI, connecting to SQL Server from Java, eclipse connect to SQL Server, Failed to load the sqljdbc_auth.dll cause :- no sqljdbc_auth in java.library.path, java.sql.SQLException: I/O Error: SSO Failed: Native SSPI library not loaded. Check the java.library.path system property, jdbc, jtds, SQL Server Windows authentication, executing SQL Server stored procedure from Java, calling SQL Server user-defined-function (UDF) from Java, SQL Server multiple tables ResultSets

This entry was posted in General and tagged , , , , , , , , , , , , . Bookmark the permalink.

92 Responses to Connecting to SQL Server from Java

  1. rachit says:

    import java.sql.*;
    public class conection
    {

    public static void main(String a[]) throws ClassNotFoundException, SQLException
    {

    try
    {
    String url = “jdbc:sqlserver://agarwal-pc\\SQLEXPRESS;databaseName=CHAT”;
    Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
    Connection conn = DriverManager.getConnection(url);
    System.out.println(“connection created”);
    Statement st=conn.createStatement();
    String sql=”select * from CHAT”;
    ResultSet rs=st.executeQuery(sql);
    while(rs.next())
    {
    System.out.println(“Name: “+rs.getString(1));
    //System.out.println(“Address : “+rs.getString(2));
    }
    if(st!=null)
    st.close();
    if(conn!=null)
    conn.close();

    }
    catch(SQLException sqle)
    {
    System.out.println(“Sql exception “+sqle);
    }
    }

    // TODO Auto-generated method stub

    }

    i am this exception.please tell me how to resolve this
    Sql exception com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host agarwal-pc, named instance sqlexpress failed. Error: “java.net.SocketTimeoutException: Receive timed out”. Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.

    • So it doesn’t print ‘connection created’ right? Well, not entirely sure what’s going on, but here are a few things you can try:
      1. Looking at your code, it seems like you’re using integrated security, in which case try setting integratedSecurity=true (case 1 in this post).
      2. Have you enabled tcp/ip – see first point under ‘Resolution’ here – https://thusithamabotuwana.wordpress.com/2012/01/08/connecting-to-sql-server-using-jtds/.
      3. Make sure SQL Server Browser service is started.
      4. Right click and look under database properties in SSMS to make sure the connection string is right.
      5. Try the jtds driver (link under second point) to see if that works. If that works, you know it’s a jdbc related error. I also had some trouble intially with the jdbc driver when jtds was working just fine!

    • Malarchist says:

      Your default server name might be “MSSQLSERVER” and not “SQLEXPRESS” depending on which version of SQL Server you are using.

  2. Bumble says:

    Thusitha, thank you for this page – your directions are very clear.

    I am using method two and have a simple question about the .jar files for the JDBC driver. The sqljdbc4.jar is included in the build path, but I am still getting a “ClassNotFound” error related to the lines below.

    Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
    Connection conn = DriverManager.getConnection(url, userName, password);

    I am not sure what the trouble is and am hoping you might help.

    Thanks.

    • Well, it’s difficult to pinpoint the exact reason for this without seeing at least the stacktrace, but in your build path have you correctly pointed to the sqljdbc4.jar in ‘Microsoft JDBC Driver 4.0 for SQL Server’ folder? You need all other files that go along with it as well and simply having only the .jar won’t do. I have updated the post as well to reflect this point.

  3. jorgeklemm says:

    Congractulations Bro!!!

    Solve my problem with jTDS and Windows Authentication! So, instead of add the path of SSO on my JVM, I just copy the ntlmauth.dll to the bin directory of my JRE instalation and restart all apps.

    Thanks a lot! Your Blog is a really good value!

  4. Eduar says:

    Gracias excelente tutorial me fue de mucha ayuda
    thank

  5. Eduar says:

    Otra alternativa de asociar el archivo sqljdbc_auth.dll es copiar este archivo al System32, fijarse si estamos usando la java para 64 bits o 84bits, y extraer el que correponda.

    Saludos

    • Thanks for the comments Eduar..happy to hear it helped :-). Also, thanks for your alternative solution. I’ve translated it so that the English speakers could also make use of this alternative approach.

      “Another alternative is to associate the file sqljdbc_auth.dll copy this file to the System32 folder, look if we are using java for 64 bit or 84bits, and remove that correspondence.”

  6. Olga says:

    You are awesome! You have no idea how long I’ve been looking for such a clear example and explanation. Thank you so so much for posting this!

  7. Anonymous says:

    how am not still able to connect. What should be username and password.

    • Well, usename/password would be what YOU use to connect to your SQL Server. If you didn’t set it up, perhaps you can talk to your admin to find out what the connection details are? Make sure you can connect to your server via SQL Server Management Studio first before you try to connect programmatically. Otherwise you don’t know if it’s a login credential related issue, or some sort of a connection string issue.

  8. mika79 says:

    thanks a lot for putting this together – it was a great help!

  9. Bryan says:

    Hi Thusitha,
    This method works great (JDBC + Windows Auth) from within Eclipse, but I need to export and distribute my program. When I export to a jar I am getting the same error message;
    “Jul 16, 2012 10:02:20 AM com.microsoft.sqlserver.jdbc.AuthenticationJNI
    WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path”

  10. kunal ghosh says:

    plz help me…. how to connect SQLServer using windows authentication over network in java. When connect in local machine that works fine. my java code is —-
    Class.forName(“com.microsoft.sqlserver.jdbc.SQLServerDriver”);
    con = DriverManager.getConnection(“jdbc:sqlserver://sandesh-think:1433;databaseName=AdventureWorksLT;integratedSecurity=true”);

    and errors are—-
    com.microsoft.sqlserver.jdbc.SQLServerException: Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
    at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
    at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2532)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1929)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1917)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1061)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
    at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:207)
    at test.Example.main(Example.java:79)

    • Hi Kunal,

      First of all, can you connect to your network SQL Server through Management Studio? To test this, fire up Management Studio, and specify the network server name (which would look like SERVER_OR_MACHINE_NAME\SQLEXPRESS2012 for instance) and select ‘Windows Authentication’. This would include your Windows credentials by default. Make sure you can connect to your network instance in this way first before trying to connect programmatically. If you can, then you know it’s a connection string issue in the code; if you can’t, then it could be a permission issue. If it’s a permission issue, you need to make sure you have the correct permissions for this SQL instance. Get your admin to give you permission; or else, if you are the admin, may be RDP into the remote machine, log in as admin, and add your Windows network credentials to ‘Permissions’ under ‘properties’ (right click on instance name in Management Studio -> Properties).

      If you can connect to the network instance through Management Studio, then it’s a connection string issue. Try the following:
      String conn = “jdbc:sqlserver://SERVER_OR_MACHINE_NAME\\SQLEXPRESS;databaseName=dbname;username=domain\windowsLogin;integratedSecurity=true”;

      Hope this helps!

  11. Diya! says:

    Thanks a lot for this detailed post. This helped me resolve a long time pending DB connection issue. No other forum or blog has such a detailed issue.

  12. Pingback: solve error in connection between sql server 2008 r2 with java in eclipse | Jisku.com - Developers Network

  13. Hi! Thanks for this post!

    Please, does this entry apply only to Java running in Windows machines?

    I’m trying hard to connect a couple of R (http://www.r-project.org/) instances running in Mac OS X and Ubuntu boxes to a MS SQL Server 10 repository. I use a library, RJDBC, that uses a JDBC driver. I must use Windows Authentication as it is the only way I’m allowed to access this server.

    Please, has anybody connected to a MS SQL Server server from a non-Windows box by using JDBC and Windows Authentication?

    If yes, please, could you provide us a sample of the connecting string?

    Thanks for your work! Thanks for your help!

    Ricardo

  14. Anonymous says:

    thank you very very much..without this i dont knnow how I would have done my work..

  15. Hi there, I’m having this problem.

    Error Trace in getConnection() : The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “Unable to make socket non blocking”

    I’d appreciate if anybody knows something to solve this

    I’m getting mad… Thanks

  16. Mohit Goyal says:

    Thusitha – I would like to thank you for your effort. No other posts or references are as detailed and useful as this. Got me working in a jiffy !! Thanks for sharing.

  17. About Java says:

    awesome article.. informative and clear steps connecting sql server from java.. thanks.. 🙂

  18. Charles says:

    getting an error about connection refused references that the port isnt open Windows 7 but I just went into windows FW and made that specific port available Grrrrrrr!!!!

    • hmm..I’m not sure if you still have an issue, or you managed to get it fixed after making ‘that specific port available’. I don’t recall ever encountering the port issue you have mentioned, but if you post some details perhaps someone might be able to help.

  19. Gayatri says:

    Hi, I want to use Windows authentication with JTDS to connect to MSSQL server. The url used is: “jdbc:jtds:sqlserver://10.30.195.56;databaseName=HA;instance=SQLEXPRESS;useNTLMv2=true;domain=corp.emc.com;login=NT Authority\\SYSTEM”
    If I change the databaseName=msdb, the url works. But I want to connect to my database which I have named HA and has used login as “test” and password as “test” while creating it. I get the following errir:

    java.sql.SQLException: Cannot open database “HA” requested by the login. The login failed.
    at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:368)
    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:610)
    at net.sourceforge.jtds.jdbc.ConnectionJDBC2.(ConnectionJDBC2.java:345)
    at net.sourceforge.jtds.jdbc.ConnectionJDBC3.(ConnectionJDBC3.java:50)
    at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
    at java.sql.DriverManager.getConnection(DriverManager.java:579)
    at java.sql.DriverManager.getConnection(DriverManager.java:243)
    at com.gitz.Test.main(Test.java:32)

    • Hi Gayatri,

      I’m not sure exactly what’s going on, but you can’t use Windows authentication and a username+password to connect (as far as I know at least). Since you have mentioned you need to use a username and a password I’m assuming you want to go with that option instead of Windows authentication. Have you tried the 4th option mentioned in this post with that connection string? Also, please take a look at one of the prior posts where I was also connecting to SQL Server using jTDS with a username+password (https://thusithamabotuwana.wordpress.com/2012/01/08/connecting-to-sql-server-using-jtds/). The specific error you have mentioned is a bit different, but I was also getting some portions of your stacktrace:

      at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:368)
      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:610)

      so perhaps there’s some connection there? Let me know how it goes.

  20. Gayatri says:

    Thanks for the reply. I am able to resolve my error by adding my Windows user in the SQL Server Management Studio.

  21. Gayatri says:

    One more question: To use windows authnetication, do both the SQL server and the client machine be in same domain or trusted domain.

    • Happy to hear you managed to resolve your issue. As to the domain, I believe they need to on the same domain, but I’m really not sure. Never tried connecting to a server outside the domain the client machine was on, so can’t really comment on that..sorry.

  22. Bambino says:

    This was really helpful. Thank you. 🙂

  23. Octavian says:

    You just saved my day ! Good job and tx .

  24. Anonymous says:

    I for all time emailed this weblog post page to all my friends working with Java,
    for the reason that if I found it useful, my friends will too.

  25. Nic says:

    Thank you, thank you, thank you. I had spent so much frustrating time trying to get my connection to work using just the command line in Windows. Downloaded Eclipse, followed your samples and worked first time. You have done a great service here. I don’t know how many websites I went through and could not find exactly what would make it work until I found yours.

  26. Malarchist says:

    Thanks for the article. It helped a lot. I think I should just add that the default name of the server instance may be “MSSQLSERVER” and not “SQLEXPRESS”. You can check this with SQL Server Configuration Manager

    • Good point. I think the default instance depends on the version you installed. In my case it was SQLEXPRESS, but on some of the other machines I have seen MSSQLSERVER being the default instance. I have updated the post to reflect your comment. Thanks.

  27. android developer says:

    My dear friends..
    Im developing a small android app using Android Development Tools. Now I want to connect ADT with mssql 2008. I used JDBC 4.0. I attached the sqljdbc4.jar to my project and also to the java build path, libraries. Here is some code I used..

    String connString = “jdbc:sqlserver://;databaseName=”;
    String username = “”;
    String password = “”;
    conn = DriverManager.getConnection(connString,username,password);

    I also used several connection strings like below..

    String connString = “jdbc:sqlserver://;databaseName=”;
    String connString = “jdbc:sqlserver://;databaseName=”;
    String connString = “jdbc:sqlserver://;databaseName=;instance=SQLEXPRESS;”;

    but Im getting this error while connecting to the database
    Error:
    The TCP/IP connection to the host , port 1433 has failed. Error: “socket failed: EACCES (Permission denied). Verify the connection properties, check that an instance of SQL server is running on that host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.*.

    Im sure I have configured the mssql server 2008 TCP/IP connection with port 1433. My TCP/IP connection in mssql is enabled and I have assigned 1433 to IP All TCP Port.
    but still getting the above error..
    Im really appreaciate if anyone can answer to my question and help me to connect my app with mssql.

    thank you.

    • android developer says:

      before I didnt give the permission in manifest then the error message was

      Error
      The TCP/IP connection to the host , port 1433 has failed. Error: “socket failed: EACCES (Permission denied). Verify the connection properties, check that an instance of SQL server is running on that host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.*.

      but after I gave the permision in manifest error was
      null exception

      please help me on this

      thank you

  28. android developer says:

    Hi thusitha
    thank you for your reply
    I used windows authentication also but the same error, null exception.
    what ever the connection string is the output would be null exception
    even if I give it like this, same error
    String connString = “jdbc:sqlserver://”;
    Error Exception: null
    but if I change any letter in the above connection string the error would be different.
    String connString = “jdbc:sqlserver:/”;
    Error Exception: no suitable driver
    what would be the error in my application??
    make sure Im using android development toolkit which includes eclipse platform, jdt, cdt,emf. gef and wtp and java runtime 7 with jdbc 4.0
    thank you

    • android developer says:

      Hi thusitha
      I found this error in the LogCat
      Could not find class ‘javax.sql.XAConnection’, referenced from method com.microsoft.sqlserver.jdbc.SQLServerConnection.poolCloseEventNotify
      what could be the reason for this error??
      this error throws when passing this line..
      conn = DriverManager.getConnection(connString);

      • hmm..I’m no expert in Android development, but if you search this page for ‘android’, you’ll see a prior post as well where someone was having trouble connecting to SQL Server. Can you connect to your SS instance as a regular Java app? If so, you know your DB is set up properly, accepting connections and all, and that it’s something to do with the Android platform. Sorry..I have no experience with Android dev, so not sure what to suggest.

  29. Developer says:

    Good article! We will be linking to this great post on our website.
    Keep up the great writing.

  30. android developer says:

    Hi thusitha
    I found the solution to the above error and now I got another one.
    Error:
    W/Error connection(854): The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “Socket closed”.
    any idea how to solve this??
    thanks

    • Mind sharing what the fix was for the previous error? Others might find it useful.

      As for the socket error, there’s something related here – http://comments.gmane.org/gmane.comp.handhelds.android.devel/172167. Someone’s basically suggested a couple of options –
      – Setting up SQL Server to accept non-SSL connections (you might need to Google how to do this)
      – Using jTDS driver. Somewhere else also I read that this socket closed error is JDBC related. Plus, in that thread the poster has said the jTDS driver worked perfectly, so you might want to try that.

      • android developer says:

        Technically it is not possible to perform network IO on the UI thread on newer versions of android (most probably after honeycombe). To solve this there are two ways, you can set the targetSdkVersion to gingerbread or earlier version. Second option is to add this code in your class.
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);

      • Great, thanks for posting the solution!

  31. android developer says:

    hello everyone
    after a huge struggle I found the solution..
    jdbc 4.0 not worked for me.
    Error:
    W/Error connection(854): The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: “Socket closed”.
    jtds-1.3.1 also not worked.
    but jtds-1.2.5 worked for me. I suggest to use jtds-1.2.5 for those who want to connect ADT with MSSQL.

  32. ann says:

    i have made the following as main class for connection to sql server…but it’s not working…

    package leave;

    import java.sql.Connection;
    import java.sql.DriverManager;

    public class Main
    {
    public static Connection getCon()throws Exception
    {
    Connection con=null;
    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
    con=DriverManager.getConnection(“jdbc:odbc:javasql1”);
    return con;
    }

    }

    • You don’t say what’s not working, but it’s possible it’s a driver issue. Seems like you are trying to use the JdbcOdbc driver/bridge instead of the JDBC/jTDS drivers mentioned in the post, in which case the class should be “com.microsoft.sqlserver.jdbc.SQLServerDriver” or “net.sourceforge.jtds.jdbc.Driver”. Let me know how it goes..

  33. ann says:

    it’s giving the following error:-
    java.lang.classnotfoundexception:com.microsoft.sqlserver.jdbc.sqlserverdriver

  34. ann says:

    Now it’s showing :
    warning: [options] bootstrap class path not set in conjunction with -source 1.5

  35. Pingback: JDBC to MSSQL | Bookie Oandasan

  36. Triguna says:

    Awesome post Thusitha Mabotuwana. Thanks for posting it.

    Its very common nowadays to use JPA and I am trying with it right now. Can you please guide me do the exact same thing using JPA? Esp., Spring JPA. On another note: does this procedure works well with Spring JPA as well? I doubt…

    I tried googling it, but I am a newbie to SQL Server. Please help me.

    Thanks,
    Triguna

  37. Anonymous says:

    Hi Thusitha,
    I am developing an ADF Mobile app in JDeveloper that should connect to Sql Server DB. I included a driver file in C:\Oracle\Middleware\jdeveloper\jdev\lib\sqljdbc4.jar but I am still getting error when I import java.sql.DriverManager.I even included sqljdbc4.jar file in project properties. Please help me solve this problem. Thanks.

  38. books says:

    Good topic.
    Thanks for excellent info I was looking for this information for my mission.

  39. very helpful. Cheers for writing this post.

  40. Manal says:

    Concise and very well-explained. Thank you!

  41. Larry Buta says:

    This is an excellent post…very helpful. I haven’t done much previously using JDBC but that will change due to a project I am working on. So getting up to speed on the JDBC API is critical and this helped immensely. Thanks for taking the time to write it….

  42. Abigail says:

    Hi After an entire morning of struggle, your post finally helped. however I was not able to use the jdbc+windows authentication, i kept getting the ‘sqljdbc_auth not in path error.
    But worked in a jiffy when i tried using jtds. Btw, we have a sql server 2012 and I connect over network.

    • Thanks for taking the time to post a comment. I assume you added the path to sqljdbc_auth.dll as a VM argument? Only other point to remind would be to use the JDBC 4.0 driver since SQL Server 2012 requires 4.0.

  43. David says:

    This is sick. My head exploded. You have solved my probs wrt JDBC and Windows. Abigail – you have to have the auth path EXACTLY correct. As in , it should be the directory (not the file), the apostrophes should be in the correct place and be of the correct type. That’s the only difficulty I had.
    BR
    Dave

  44. swaroop says:

    thanks…………

  45. dario90 says:

    Briefly:

    1- Download the JDBC driver and uncompress it
    2- Secondary click in the root of the Eclipse project and go to “Properties”.
    3- Now go to the section “Java Build Path – Libreries” y then click “Add External JARs”.
    4- Search the “sqljdbc.jar” file in the directory where you unpacked the downloaded driver, double click y finish pressing “ok”.

    Then you can connect to the database:

    String driver = “com.microsoft.sqlserver.jdbc.SQLServerDriver”;
    String server = “jdbc:sqlserver://localhost:1433;databaseName=your_database_name”;
    String usr = “your_user_name”;
    String psw = “your_password”;

    Class.forName(driver);
    dbConn = DriverManager.getConnection(server,usr,psw);
    statement = dbConn.createStatement();

    String tableName = “your_table_name”;
    ResultSet = statement.executeQuery(“select * from “+ tableName);

    I’m sorry for my english. Bye.

  46. Pingback: How To Fix Java Manual Download For 1.6.0_37 Errors - Windows Vista, Windows 7 & 8

  47. Pingback: Fix Razorsql Error Windows XP, Vista, 7, 8 [Solved]

  48. Pingback: How To Fix Java Error=7 Argument List Too Long in Windows

  49. Anonymous says:

    Thanks mate really help me !!!! for 24 hrs i was Struggling to find the solution use different bridge still did not works really hellp me 😀

  50. Anonymous says:

    i need the connection of sql server windows authentication code for servlet.

  51. Manuel says:

    Actually the Phrase “we have two commonly used drivers – JDBC and JTDS.” is not 100 percent correct since both drivers are JDBC Type IV Drivers.
    I think it would be more correct if you called them “MsJdbc” and “JTDS”, “SqlServerJDBC” and “JTDS” or so.
    Also something worth mentioning is the fact that JTDS doesn’t support Connection Pooling.

  52. abaupene says:

    i want to connect to sql server 2008 with java, but i have the messge error like “Integrated authentication failed”. So, it’s work fine in eclipse but after deploying the application in tomcat 8, i have an error message. Thank you for your support.

  53. Noel says:

    Holy cow… String url =”jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB really works…
    thanks so much…

  54. Here’s something that may help with login errors, sometimes ir’s necessary to enable the SQL Server Browser, going to SQL server configuration manager> SQL Server services > SQL Server Browser, > Properties > Service > Start Mode > automatic and then restart Sql server browser

  55. Pingback: How do I connect to a SQL Server 2008 database using JDBC?

  56. Pingback: How do I connect to a SQL Server 2008 database using JDBC? – Row Coding

Leave a reply to Bumble Cancel reply