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 drivers – MS-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):
- Windows authentication + JDBC
String url ="jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(url);
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
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);
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);
’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.
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);
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(); }
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
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!
Your default server name might be “MSSQLSERVER” and not “SQLEXPRESS” depending on which version of SQL Server you are using.
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.
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!
Thanks for your comments Jorge 🙂 Always happy to hear someone else finding what I write useful!
Gracias excelente tutorial me fue de mucha ayuda
thank
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.”
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!
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.
thanks a lot for putting this together – it was a great help!
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”
Hi Bryan,
I haven’t tried to deploy, so not 100% sure how to fix this, but would this help – http://www.coderanch.com/t/544587/JDBC/databases/no-sqljdbc-auth-java-library? Seems like this person was having the same problem where it was building fine in Eclipse, but was getting errors when trying to deploy. Also, here are a few other links you might want to take a look at:
http://stackoverflow.com/questions/1611357/how-to-make-a-jar-file-that-include-dll-files
http://fjep.sourceforge.net/
http://one-jar.sourceforge.net/
Please let me know if you figure out what the issue is. I’ll try it out myself and update the post if I find a solution.
Copy sqljdbc_auth.dll from C:\sqljdbc_3.0\enu\auth\x86 folder to your jdk/bin directory.
Alternatively, if you are using 64 bit JVM, copy it from x64 folder. It worked for me.
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!
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.
Pingback: solve error in connection between sql server 2008 r2 with java in eclipse | Jisku.com - Developers Network
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
Hi Ricardo,
I have never tried these connection strings on a non-Windows machine, so unable to comment. According to the JDBC download site, the supported operating systems are Linux, Unix, Windows 7, Windows Server 2008 R2 and Windows Vista (see http://www.microsoft.com/en-us/download/details.aspx?id=11774), so unlikely you are going to have any luck with JDBC.
However, it looks like jTDS should still work. Take a look at these links and see if they help:
http://www.razorsql.com/articles/sql_server_mac.html
http://stackoverflow.com/questions/9844990/jdbc-jtds-and-mac-osx-app-with-xcode-4-3
http://stackoverflow.com/questions/11234931/windows-authentication-for-sql-server-using-jbdc-on-a-mac
http://forums.visokio.com/discussion/1633/macs-jtds-error
Hi Thusitha!
I usually think about Mac OS X as “another Unix” and, even though there are some oddities, it seems a good method! In this case, I’d tried RazorSQL before my previous post to no avail. But after your reply I’ve tried again and I can connect now to MS SQL Server 10.00 from a Mac Pro running Mac OS X 10.6.8, Java “1.6.0_37”, Windows Authentication and the jTDS bundled with RazorSQL 6.0.0 (jtds12.jar).
I did something wrong the first time, but I’m not able to find the failure.
Now I “only” need to figure out the syntax I must use in R to correctly configure the connection!
I’ll keep this thread updated with any new or doubt! Thanks for your input!
Happy to hear it’s working now Ricardo. Hopefully your post/reply will also help other folks out there!
It was easier than expected! As usual, once you know how to do it, it is easy to do it!
Sticking to the driver release bundled with RazorSQ, here the lines required in R to get a nice answer from a given MS SQL Server database:
library(RJDBC)
drvmssql <- JDBC("net.sourceforge.jtds.jdbc.Driver", "/Applications/RazorSQL.app/Contents/Resources/Java/drivers/jtds/jtds12.jar")
conmssql <- dbConnect(drvmssql, "jdbc:jtds:sqlserver://hostname:port/database;domain=domainname;ssl=request;useCursors=true", user = "username", password = "password")
## I'm adding a line just to check that the connection is effective and it is functioning correctly. It will list all tables in the given database
dbListTables(conmssql)
Once again, thank you so much for your help! I'll keep subscribed to this post trying to answer any further doubt.
Cheers!
Great news..and thanks for the feedback on the solution that worked!
very useful post … sql dba
thank you very very much..without this i dont knnow how I would have done my work..
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
Looks like “getConnection()” is your own method where the connection gets established eh? Also, why not give some context so that others can help? A quick Google search indicates that you are trying to connect from Android; is this the case? Here are a couple of forums that sound related – http://social.msdn.microsoft.com/Forums/zh/sqldataaccess/thread/88e612ea-a6ea-4f2e-9212-af516df0ba02 and https://groups.google.com/forum/?fromgroups=#!topic/android-developers/XCx53CR49Hs.
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.
awesome article.. informative and clear steps connecting sql server from java.. thanks.. 🙂
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.
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.
Thanks for the reply. I am able to resolve my error by adding my Windows user in the SQL Server Management Studio.
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.
This was really helpful. Thank you. 🙂
You just saved my day ! Good job and tx .
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.
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.
Happy to hear it helped Nic..and thanks for taking the time to post a comment 🙂
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.
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.
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
Not sure if this would help or not, but have you taken a look at this – https://thusithamabotuwana.wordpress.com/2012/01/08/connecting-to-sql-server-using-jtds/? Since you’re using the username/password option, I wonder if you need to set up the user within your server? Also, have you tried with Windows Authentication? If that works, and the username/password option doesn’t, it might help you narrow down the problem.
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
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.
Good article! We will be linking to this great post on our website.
Keep up the great writing.
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.
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!
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.
Great, thanks for sharing what worked! Sorry I couldn’t be of much help..
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..
it’s giving the following error:-
java.lang.classnotfoundexception:com.microsoft.sqlserver.jdbc.sqlserverdriver
You need to follow the instructions on this page step-by-step. You can’t just run that piece of code without adding the class libraries to path (i.e., the jar files) .
Now it’s showing :
warning: [options] bootstrap class path not set in conjunction with -source 1.5
Pingback: JDBC to MSSQL | Bookie Oandasan
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
Thanks Triguna. As much as I’d like to help, this is the first time I’m even hearing about ‘JPA’. Would these links help:
http://stackoverflow.com/questions/10415643/jpa-connection-configuration-for-sqlserver
https://groups.google.com/forum/#!topic/play-framework/EWgmMjrZV7s
http://forum.springsource.org/showthread.php?128344-Spring-Data-REST-Connecting-for-example-to-a-mssql-db-config&s=75a95bd646b321c25244b52dfd2a163d
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.
Well, I’ve never developed mobile apps that connect to a DB, so I’m not in a position to offer you much help unfortunately. Googling around a bit pretty much gives me what you have posted at http://stackoverflow.com/questions/19174500/how-to-connect-adf-mobile-to-sql-server-db so hopefully you’ll get some help there. In the meantime, http://queforum.com/programming-languages-basics/225209-java-how-connect-adf-mobile-sql-server-db.html seems to be having the same problem as you (with no solution though).
Btw, take a look at http://www.oracle-java.com/article/4775442/Oracle+DB+Access+ADF+Mobile too.
“This is not in the current feature set. We favor web services, either SOAP or REST, for back-end integration.” and “Accessing the DB directly using JDBC from the mobile device is not supported today and isn’t likely to be supported in the future either. JDBC is too chatty for mobile scenarios, and I find it hard to believe that companies would allow this type of direct access from mobile devices to their database due to security restrictions.” – so it is very likely that there simply is no way to do what you want other than exposing your DB via Web Services.
Good topic.
Thanks for excellent info I was looking for this information for my mission.
very helpful. Cheers for writing this post.
Concise and very well-explained. Thank you!
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….
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.
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
thanks…………
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.
Pingback: How To Fix Java Manual Download For 1.6.0_37 Errors - Windows Vista, Windows 7 & 8
Pingback: Fix Razorsql Error Windows XP, Vista, 7, 8 [Solved]
Pingback: How To Fix Java Error=7 Argument List Too Long in Windows
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 😀
i need the connection of sql server windows authentication code for servlet.
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.
Ok, thanks. Updated the post to reflect your point.
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.
Have you specified integratedSecurity=true? It sounds like the user access hasn’t been setup properly? May be these posts will help:
http://stackoverflow.com/questions/830929/database-windows-authentication-username-password/
http://stackoverflow.com/questions/4629718/how-can-i-connect-to-sql-server-using-integrated-security-with-the-jdbc-driver
http://stackoverflow.com/questions/31156834/tomcat8-loading-wrong-sql-server-driver-sqlserverxadatasource-not-found
Sorry, it’s been years since I last worked with tomcat, so can’t really help.
Holy cow… String url =”jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB really works…
thanks so much…
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
Pingback: How do I connect to a SQL Server 2008 database using JDBC?
Pingback: How do I connect to a SQL Server 2008 database using JDBC? – Row Coding