Prepared statement only throws exception when not debugging - java

I use this piece of code to insert some data into database:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:war_odbc");
PreparedStatement st =
con.prepareStatement(
"INSERT INTO Actors(FirstName,LastName,Age) VALUES(?,?,?)" );
st.setString(1, "Robert");
st.setString(2, "de Niro");
st.setInt(3,45);
st.executeUpdate();
con.close();
If I use debugger and step one line at a time, everything goes well. If I don't use it and just run the application, I get this exception:
[Microsoft][ODBC Driver Manager] Invalid string or buffer length
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.buildTypeInfo(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
I am using Windows 7 64 bit.
I went to Administrative Tools, Data Sources(ODBC) and i successfully tested it.

The best solution is to stop using this class from sun package (Why Developers Should Not Write Programs That Call 'sun' Packages). Also this driver is really old, it's a type 1 driver that convert JDBC calls in ODBC calls.
Now almost all DB vendors have implemented type 4 driver. This driver implementation converts JDBC calls directly into a vendor-specific database protocol.
Also according to this documentation this bridge will be removed in JDK8 so it's bad idea to use it if you want a portable / adaptable solution.

Replace st.setInt(2, "de Niro"); with st.setString(2, "de Niro");

Just few points regarding the code snippet provided.
st.setInt(2, "de Niro");
Here you are setting "string" as second parameter of query but you have used setInt() method and thats incorrect.
Is itsomething related to your OS . i mean are u using 64-bit widows OS and 32 bit connector. i am not sure about it though.
Check this link.
"[Microsoft][ODBC Driver Manager] Invalid string or buffer length" error

Related

Microsoft SSAS OLAP Connection from Java Code

I am new to the concept of OLAP DB.
Please excuse me if I missed out something in the Connection String.
I am trying to connect to connect to Microsoft Analysis Server(which is in different Domain) from my System.
While Connecting I am getting below Error.
Can you please let me know, what am I doing wrong?
I have executed the Steps Mentioned in :
https://msdn.microsoft.com/en-us/library/gg492140.aspx
and referred to the below link for connection to the Cube:
http://www.matthewgodding.com/articles/2010/2/27/getting-data-from-sql-analysis-services-using-java-and-olap4.html
After connecting to the CUbe, I need to execute MDX Query.
Please find the snippet of the code I am using:
public static void main(String[] args) {
try {
Class.forName("org.olap4j.driver.xmla.XmlaOlap4jDriver");
final Connection connection = DriverManager
.getConnection("jdbc:xmla:Server=http://Remote_Server_IPAddress/OLAP/msmdpump.dll;"
+ "Catalog=MyCatalog;"
+ "User='Domian\\Username';" \\ This is the Username to login to the Server
+ "Password='Password';" \\ This is the Password to login to the Server
+ "Cube=Cube;"); \\This is the Cube Name
I get the below Exception when I execute the program:
Exception:
java.lang.RuntimeException: org.olap4j.OlapException: This connection encountered an exception while executing a query.
at org.olap4j.driver.xmla.DeferredNamedListImpl.getList(DeferredNamedListImpl.java:96)
at org.olap4j.driver.xmla.DeferredNamedListImpl.size(DeferredNamedListImpl.java:116)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.getOlapDatabase(XmlaOlap4jConnection.java:451)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.getDatabase(XmlaOlap4jConnection.java:444)
at org.sid.practise.CheckConnection.main(CheckConnection.java:79)
Caused by: org.olap4j.OlapException: This connection encountered an exception while executing a query.
at org.olap4j.driver.xmla.XmlaHelper.createException(XmlaHelper.java:43)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.executeMetadataRequest(XmlaOlap4jConnection.java:878)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getMetadata(XmlaOlap4jDatabaseMetaData.java:137)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getMetadata(XmlaOlap4jDatabaseMetaData.java:67)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getDatabaseProperties(XmlaOlap4jDatabaseMetaData.java:1044)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.makeConnectionPropertyList(XmlaOlap4jConnection.java:324)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.generateRequest(XmlaOlap4jConnection.java:1037)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.populateList(XmlaOlap4jConnection.java:849)
at org.olap4j.driver.xmla.DeferredNamedListImpl.populateList(DeferredNamedListImpl.java:136)
at org.olap4j.driver.xmla.DeferredNamedListImpl.getList(DeferredNamedListImpl.java:90)
... 4 more
Caused by: org.olap4j.driver.xmla.proxy.XmlaOlap4jProxyException: This proxy encountered an exception while processing the query.
at org.olap4j.driver.xmla.proxy.XmlaOlap4jHttpProxy.getResponse(XmlaOlap4jHttpProxy.java:181)
at org.olap4j.driver.xmla.proxy.XmlaOlap4jAbstractHttpProxy.get(XmlaOlap4jAbstractHttpProxy.java:181)
at org.olap4j.driver.xmla.proxy.XmlaOlap4jHttpProxy.get(XmlaOlap4jHttpProxy.java:42)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.executeMetadataRequest(XmlaOlap4jConnection.java:876)
... 12 more
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.io.BufferedInputStream.fill(Unknown Source)
at java.io.BufferedInputStream.read1(Unknown Source)
at java.io.BufferedInputStream.read(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.http.HttpClient.parseHTTP(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at org.olap4j.driver.xmla.proxy.XmlaOlap4jHttpProxy.getResponse(XmlaOlap4jHttpProxy.java:136)
It's difficult to know what went wrong for you. Few things you could do,
Don't specify cube in connection. This is not listed as property in XMLA driver.
You can install fiddler and see what's going on with the requests.
Not sure if single quotes are needed in user name and password.

SQL result limit from Java application with spring-boot and DB2 database

I'm trying to limit the sql result from some statements, for example to 100 from an application in Java using spring-boot, and a DB2 database in an AS400.
I've tryied this two things, extending a CrudRepository
public List<AcumuladoEstadistico> findFirst10BySincroEstado(String aEstado);
and also this
#Query(name="FROM AcumuladoEstadistico a WHERE a.sincroEstado = ?1 limit 5", countQuery="10")
Iterable<AcumuladoEstadistico> findFirst10BySincroEstado(String aEstado);
but in both cases I have the following error
Caused by: java.sql.SQLException: [SQL0104] Símbolo LIMIT no válido. Símbolos válidos: FOR SKIP WITH FETCH ORDER UNION EXCEPT OPTIMIZE.
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:650)
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:621)
at com.ibm.as400.access.AS400JDBCStatement.commonPrepare(AS400JDBCStatement.java:1557)
at com.ibm.as400.access.AS400JDBCPreparedStatement.(AS400JDBCPreparedStatement.java:193)
at com.ibm.as400.access.AS400JDBCConnection.prepareStatement(AS400JDBCConnection.java:2025)
at com.ibm.as400.access.AS400JDBCConnection.prepareStatement(AS400JDBCConnection.java:1824)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
at com.sun.proxy.$Proxy61.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:162)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186)
... 69 more
Why I have this problem, maybe Hibernate doesn't create the statement properly for DB2? What can I do?
Thanks a lot!
Finally I've found the problem, I was using an incorrect dialect in the properties of sping
Thanks a lot!

SQL-Database and Java

I read quite a few articles here about how to connect from java to a mysql database. Somehow, this does not work for me, and I cannot find out what I do wrong. First, here is my code:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
class sqltest{
private static int uid = -1;
protected static Connection dbConn = null;
public static void main (String args[]){
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet rs = null;
try{
dbConn = DriverManager.getConnection("jdbc:mysql://XXX.XXX.XX.XX:XXXX/peXXXXX","XXXXXX","XXXXXX");
PreparedStatement ps = dbConn.prepareStatement("select id from supervisor where username = philipp");
rs = ps.executeQuery();
uid = rs.getInt("id");
}catch(SQLException e){
e.printStackTrace();
}
System.out.println(uid);
}
}
The connection details (user, password, adress) are correct. There is only one thing I don't understand: There is already a java-web-applet which is establishing such a connection, and it uses no port (is this possible?).
Now these are my errors that I get:
When I use no port or the default 3306 port, i get this error:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection timed out: connect
STACKTRACE:
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:173)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:268)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2745)
at com.mysql.jdbc.Connection.<init>(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at sqltest.main(sqltest.java:27)
** END NESTED EXCEPTION **
Last packet sent to the server was 28 ms ago.-1
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2820)
at com.mysql.jdbc.Connection.<init>(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at sqltest.main(sqltest.java:27)
I assume that this is caused by a wrong port. Is this right?
When I use the port that i assume is the right one, I get no error, but the program just runs endlessly and will not come to any result.
Thx for any help!
Make sure you're connecting to the right host/port and that these are accessible.
To do this, e.g. open a terminal and type telnet <host> <port> from the same
machine on which you're running the Java code.
I did a quick online port scan for that address and it looks like the server side is not listening on port xxxxx. Maybe firewall configuration? Or just stopped server/wrong address.
Yes,
a wrong port may cause this exception. The statement looks wrong. If you have more that a million records in the table you might wait days.
Running endlessly seems very unusual given there are no loops in your code. My guess is the SQL query is taking a very long time.
Warning: this code is wrong!
PreparedStatement ps = dbConn.prepareStatement("select id from supervisor where username = philipp");
I guess you'd need to test this against MySQL to be sure, but in most databases I have worked with, an unquoted string literal like that will throw an error.
Also, runtime variables in a query ought to use bind variables with a prepared statement.
In regard to the connection failure, I would say that if specifying the correct port number yields a different error than not specifying a port number, then the default port number is not the same as what you are using. That is surprising. I think 3306 is fairly well known as MySQL's default port. I am not familiar with this driver: org.gjt.mm.mysql.Driver. Try the standard MySQL driver first.
Next, since using the right port number connects, but you say it sits there, My guess is select id from supervisor where username = philipp is running long. I am still surprised it compiled given what I said earlier, but you can try running it in MySQL yourself. Bring up the mysql command-line client and run it.
If it runs slow there too, then you know it is not a Java issue. Do some tuning on it. Perhaps the username column is not indexed and you have millions of rows. Check the execution plan to know for sure.
[Edit 1]
A good technique when a program seems "stalled" is to add print statements at various points. I suggest putting a bunch of System.out.println calls to see between which lines of code are we hung? That will help you narrow the problem space.
Ok this question is answered:
The SQL-Database can be contacted from outside my university environment. But it is located on a server which is blocking my communication. Unfortunately, this was not written into the server's log-file.
Thank you guys for your help!

openfire error with no answers

I am running openfire server as a basis for my chat server, but i am not happy with the robustness of the openfire, it seems to be having lot of java errors,
java expert people who i talked to says that its all coding errors, that java exceptions hasn't handle correctly. Just want to know from a java expert is following errors are really java programming problem or a my server or settings problem.
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at org.logicalcobwebs.proxool.util.FastArrayList.get(FastArrayList.java:475)
at org.logicalcobwebs.proxool.ConnectionPool.getConnection(ConnectionPool.java:184)
at org.logicalcobwebs.proxool.ProxoolDriver.connect(ProxoolDriver.java:89)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.jivesoftware.database.DefaultConnectionProvider.getConnection(DefaultConnectionProvider.java:86)
at org.jivesoftware.database.DbConnectionManager.getConnection(DbConnectionManager.java:124)
at org.jivesoftware.openfire.spi.PresenceManagerImpl.userUnavailable(PresenceManagerImpl.java:280)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:168)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:135)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:199)
at org.jivesoftware.openfire.PresenceRouter.handle(PresenceRouter.java:149)
at org.jivesoftware.openfire.PresenceRouter.route(PresenceRouter.java:85)
at org.jivesoftware.openfire.spi.PacketRouterImpl.route(PacketRouterImpl.java:84)
at org.jivesoftware.openfire.SessionManager$ClientSessionListener.onConnectionClose(SessionManager.java:1164)
at org.jivesoftware.openfire.net.VirtualConnection.notifyCloseListeners(VirtualConnection.java:214)
at org.jivesoftware.openfire.net.VirtualConnection.close(VirtualConnection.java:190)
at org.jivesoftware.openfire.http.HttpSession$HttpVirtualConnection.systemShutdown(HttpSession.java:1008)
at org.jivesoftware.openfire.spi.LocalRoutingTable.stop(LocalRoutingTable.java:146)
at org.jivesoftware.openfire.spi.RoutingTableImpl.stop(RoutingTableImpl.java:857)
at org.jivesoftware.openfire.XMPPServer.shutdownServer(XMPPServer.java:948)
at org.jivesoftware.openfire.XMPPServer.access$700(XMPPServer.java:146)
at org.jivesoftware.openfire.XMPPServer$ShutdownHookThread.run(XMPPServer.java:898)
2012.11.24 05:50:37 org.jivesoftware.util.log.util.CommonsLogFactory - Problem
java.sql.SQLException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at org.logicalcobwebs.proxool.ConnectionPool.getConnection(ConnectionPool.java:235)
at org.logicalcobwebs.proxool.ProxoolDriver.connect(ProxoolDriver.java:89)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.jivesoftware.database.DefaultConnectionProvider.getConnection(DefaultConnectionProvider.java:86)
at org.jivesoftware.database.DbConnectionManager.getConnection(DbConnectionManager.java:124)
at org.jivesoftware.openfire.spi.PresenceManagerImpl.userUnavailable(PresenceManagerImpl.java:280)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:168)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:135)
at org.jivesoftware.openfire.handler.PresenceUpdateHandler.process(PresenceUpdateHandler.java:199)
at org.jivesoftware.openfire.PresenceRouter.handle(PresenceRouter.java:149)
at org.jivesoftware.openfire.PresenceRouter.route(PresenceRouter.java:85)
at org.jivesoftware.openfire.spi.PacketRouterImpl.route(PacketRouterImpl.java:84)
at org.jivesoftware.openfire.SessionManager$ClientSessionListener.onConnectionClose(SessionManager.java:1164)
at org.jivesoftware.openfire.net.VirtualConnection.notifyCloseListeners(VirtualConnection.java:214)
at org.jivesoftware.openfire.net.VirtualConnection.close(VirtualConnection.java:190)
at org.jivesoftware.openfire.http.HttpSession$HttpVirtualConnection.systemShutdown(HttpSession.java:1008)
at org.jivesoftware.openfire.spi.LocalRoutingTable.stop(LocalRoutingTable.java:146)
at org.jivesoftware.openfire.spi.RoutingTableImpl.stop(RoutingTableImpl.java:857)
at org.jivesoftware.openfire.XMPPServer.shutdownServer(XMPPServer.java:948)
at org.jivesoftware.openfire.XMPPServer.access$700(XMPPServer.java:146)
at org.jivesoftware.openfire.XMPPServer$ShutdownHookThread.run(XMPPServer.java:898)
This is either a problem with the parameters you are (or aren't) passing to your database driver - or possibly a bug in the database driver itself. My guess is that you aren't passing in required properties in your DB connection string.
It is certainly not a problem with openfire itself - we have used openfire for many years now, and it is an exceptional piece of software.

Create a jTDS connection string

my sql server instance name is MYPC\SQLEXPRESS and I'm trying to create a jTDS connection string to connect to the database 'Blog'. Can anyone please help me accomplish that?
I'm trying to do like this:
DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/Blog", "user", "password");
and I get this:
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:395)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at SqlConnection.Connect(SqlConnection.java:19)
at main.main(main.java:11)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:305)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:255)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:323)
... 6 more
As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC, you may end up with something like this:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t
Or, if you prefer to use getConnection(url, "sa", "s3cr3t"):
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
EDIT: Regarding your Connection refused error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.
Really, really, really check if the TCP/IP protocol is enabled in your local SQLEXPRESS instance.
Follow these steps to make sure:
Open "Sql Server Configuration Manager" in "Start Menu\Programs\Microsoft SQL Server 2012\Configuration Tools\"
Expand "SQL Server Network Configuration"
Go in "Protocols for SQLEXPRESS"
Enable TCP/IP
If you have any problem, check this blog post for details, as it contains screenshots and much more info.
Also check if the "SQL Server Browser" windows service is activated and running:
Go to Control Panel -> Administrative Tools -> Services
Open "SQL Server Browser" service and enable it (make it manual or automatic, depends on your needs)
Start it.
That's it.
After I installed a fresh local SQLExpress, all I had to do was to enable TCP/IP and start the SQL Server Browser service.
Below a code I use to test the SQLEXPRESS local connection. Of course, you should change the IP, DatabaseName and user/password as needed.:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JtdsSqlExpressInstanceConnect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "user";
String password = "password";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}
And if you use Maven, add this to your pom.xml:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
jdbc:jtds:sqlserver://x.x.x.x/database replacing x.x.x.x with the IP or hostname of your SQL Server machine.
jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS
or
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
If you are wanting to set the username and password in the connection string too instead of against a connection object separately:
jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS;user=foo;password=bar
(Updated my incorrect information and add reference to the instance syntax)
A shot in the dark, but
From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port
SQLServer runs the default instance over port 1433. If you specify the port as port 1433, SQLServer will only look for the default instance. The name of the default instance was created at setup and usually is SQLEXPRESSxxx_xx_ENU.
The instance name also matches the folder name created in Program Files -> Microsoft SQL Server. So if you look there and see one folder named SQLEXPRESSxxx_xx_ENU it is the default instance.
Folders named MSSQL12.myInstanceName (for SQLServer 2012) are named instances in SQL Server and are not accessed via port 1433.
So if your program is accessing a default instance in the database, specify port 1433, and you may not need to specify the instance name.
If your program is accessing a named instance (not the default instance) in the database DO NOT specify the port but you must specify the instance name.
I hope this clarifies some of the confusion emanating from the errors above.

Categories