Connecting with hibernate to a Microsoft SQL 2008 server - java

I am trying to connect to a Microsoft SQL 2008 server via hibernate.
The following is my hibernate.cfg.xml file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://127.0.0.1:1433;databaseName=myDBName;instanceName=myInstanceName;</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">pass</property>
<mapping resource="Obj.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And here is the code I use to try and establish an connection and do a query :
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class SessionsTest {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
/**
* #param args
*/
#SuppressWarnings({ "unchecked"})
public static void main(String[] args) {
sessionFactory = configureSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
List<Obj> result = (List<Obj>) session.createQuery("FROM Obj").list();
for (Obj obj : result ) {
System.out.println(obj.getObjID());
}
session.getTransaction().commit();
session.close();
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
private static SessionFactory configureSessionFactory() throws HibernateException {
Configuration config = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
The stacktrace I get :
2013-04-13 15:02:03,449 [main] WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 08S01
2013-04-13 15:02:03,449 [main] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - The TCP/IP connection to the host 127.0.0.1, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:221)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1425)
at com.test.test.ObjTest.main(ObjTest.java:24)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host 127.0.0.1, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1033)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:817)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:204)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214)
... 5 more
I have tried using a different driver(JTDS).
I have tried changing the URL string in various ways.
I have tried changing my dialect to org.hibernate.dialect.SQLServerDialect.
I also tried using windows authentication at one point by adding ;IntegratedSecurity=true to the end of the url string.
Other than this I have been poking around in the server properties to make sure the the instance I am providing is correct aswell as the port.I have tried : telnet localhost 1433 and can't connect that way,but I can connect using SQL Server Management Studio.
Further I used NetStat -o in cmd and TaskList /FI "PID eq 4072" /FO LIST /V to try and track down the sql server to confirm the port aswell.The weird thing is I couldn't track down sql server this way.It does not turn up in the NetStat list,but if I use the PID of the server directly it does show details about it except the Status is Unknown,Session# is 0 and User Name is N/A.
I use Hibernate 4.2.0 and SQLJDBC4,when I used JTDS it was 1.2.7.
The output of java -version :
java version "1.6.0_30"
Java(TM) SE Runtime Environment (build 1.6.0_30-b12)
Java HotSpot(TM) 64-Bit Server VM (build 20.5-b03, mixed mode)
Please tell me if any other info is needed,first time posting here.

I think your SQL Server instance is not serving at 1433 for TCP connections.
To identify the port:
Go to SQL Server configuration manager.
Choose SQL Server Network Configuration
Go for Protocols for Your Instance
Click on TCP IP (Enable it if not enabled, then clients could connect with TCP/IP)
On the popup which results, Choose IP Addresses Tab
Scroll Down
You'll see TCP Dynamic ports in Section IPAll
Grab that value and that's the port you should be using

Really, really, really check if the TCP/IP protocol is enabled in your SQL Server instance.
Follow these steps (tested for SS2012) 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 <YourInstance>"
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 SQL Server, 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 connection to a SQLEXPRESS local instance. 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>

Related

SSL error when connecting to remote SQL server using Java (netbeans)

i asked this question before but got no answers, i think mainly because it was a mess, i'll state the facts and put some quotes from the code under
im using VMWare, and have one Windows Server 2003 with SQL Server 2005 on it, with a SQL Login, and it has a DNS Service running
i also have a windows 7 machine running NetBeans8.2 with JDK 8.1, using JDBC 4.2
i can connect to the server using SQL Manager from the Windows 7 machine
i can't connect using the java code because of an SSL Error, i am not sure what is causing it
this is for a school project so i must use SQL server 2005
here's my connection code :
package connectbd;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class ConnectBD {
public static void main(String[] args) {
String jdbcurl;
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
jdbcurl = "jdbc:sqlserver://SQLSERVER;instanceName=SQLE;user=****;password=****;database=LP_SIBD_GR15";
try {
con=DriverManager.getConnection(jdbcurl);
System.out.println("Connection success");
} catch(SQLException e) {
e.printStackTrace();
}
}
}
This is the error that i get :
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to the SQL Server using Secure Sockets Layer (SSL) encryption. Error: "The SQL Server server returned no response. The connection has been closed. ClientConnectionId:e9655c34-7c66-42c8-aaec-36601b53ff98 ».
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2826)
****at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1829)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2391)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2042)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1889)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1120)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:700)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at connectbd.ConnectBD.main(ConnectBD.java:35)
Caused by: java.io.IOException:
The SQL Server server returned no response. The connection was closed. ClientConnectionId:e9655c34-7c66-42c8-aaec-36601b53ff98
****at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.ensureSSLPayload(IOBuffer.java:786)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.readInternal(IOBuffer.java:836)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.read(IOBuffer.java:829)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.readInternal(IOBuffer.java:999)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.read(IOBuffer.java:989)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1756)
... 8 more
BUILD SUCCESSFUL (total time: 1 second)
i believe the causes are somewhere in these 2 lines: the ones marked by **** at the start
i have to deliver a webservices project for school in 2 weeks, and this is kind of a huge obstacle, any quick help or suggestion would be very appreciated
You will need to add few parameters to specify the ssl connection, such as integratedSecurity=true, encrypt=true and trustServerCertificate=true.
jdbcurl = "jdbc:sqlserver://SQLSERVER;instanceName=SQLE;user=****;password=****;database=LP_SIBD_GR15;integratedSecurity=true;encrypt=true;trustServerCertificate=true";

Not able to access one database in SQL Server using Java

I have an SQL Server 2012 edition. I have two databases on this server. One of these databases named BANKTEST was restored from a backup a few months ago. I have recently restored another database named NEWBANK.
The following is the java program which I had written to access NEWBANK
package com.example.myproject.client;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectMSSQL {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1;user=sa;password=sa123;Database=NEWBANk");
System.out.println("test");
Statement sta = conn.createStatement();
String Sql = "select TOP 10 CodeType from D001002";
ResultSet rs = sta.executeQuery(Sql);
while (rs.next()) {
System.out.println(rs.getString("CodeType"));
}
}
}
Unfortunately, I am getting an error which I have listed below
> Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: Cannot open database "NEWBANK" requested by the login. The login failed. ClientConnectionId:69c57dd7-38b1-413c-b8ea-8d53824f74e1
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:254)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:84)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2908)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.example.myproject.client.ConnectMSSQL.main(ConnectMSSQL.java:13)
If I replace the name of the database with BANKTEST, I do not get any errors. Can someone advice me on this?
Regards
Sachin
The error shows that the username and password which you are using to login to your database NEWBANK is not valid or does not have the permision to access it.
You need to check your login details with your DBA and then try to login again. You can also check if you can access the database using the SQL Server Management Studio using the login credentails you are using in code.(You will probably find the same error over there as well)
You can also follow the steps given here: SQL SERVER – FIX : ERROR : Cannot open database requested by the login.
Go to SQL Server >> Security >> Logins and right click on NT
AUTHORITY\NETWORK SERVICE and select Properties
In newly opened screen of Login Properties, go to the “User Mapping”
tab. Then, on the “User Mapping” tab, select the desired database –
especially the database for which this error message is displayed. On
the lower screen, check the role db_owner. Click OK.

DatabaseException CommunicationsException: Communications link failure

I use Ubuntu & Net-beans. I make a java desktop database application from Netbeans wizard. I use MySQL database which I can open & run query from its Services → Databases. When I run it I got the Exception below. When I clean & Build the Project run jar file, same Exception. I have installed Windows in the same machine dual boot way, and also have the same MySQL database & Java. When I run the jar file I make using Ubuntu Netbeans, it perfectly run in Windows and show the database data. I did the other way also, I make the same java application in Windows Netbeans using the same database and it run perfectly both withing the Netbeans and jar file. But when I try to run it in Ubuntu, both in Netbeans & jar file show the below Exception.
[TopLink Info]: 2012.01.29 11:16:58.898--ServerSession(285416048)--TopLink, version: Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))
Jan 29, 2012 11:16:59 AM org.jdesktop.application.Application$1 run
SEVERE: Application class customerrecordsu.CustomerRecordsUApp failed to launch
Local Exception Stack:
Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Error Code: 0
at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:305)
... lot of more
Caused by: java.net.SocketException: Can't connect to SOCKS proxy:Connection refused
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:427)
... lot of more
Below is part of 'my.cnf' file removing comments.
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
user = mysql
socket = /var/run/mysqld/mysqld.sock
port = 3306
skip-external-locking
bind-address = 127.0.0.1
below is part of persistance.xml file
<property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/MyBusinessRecords"/>
<property name="toplink.jdbc.user" value="root"/>
<property name="toplink.jdbc.password" value="password"/>
Netbeans wizard use JPA, & Top Link. I make a program without wizard by pure Java, it worked perfectly in Ubuntu as expected and show the database data. That program is below. Both above and below use same Java MySQL connector.jar.
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
int id = 0;
String name = null;
try {
String url = "jdbc:mysql://localhost:3306/MyBusinessRecords";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, "root", "5843");
if (con != null) {
System.out.println("A database connection has been establised!");
st = con.createStatement();
rs = st.executeQuery("select * from COUNTRIES");
while(rs.next()){
id = rs.getInt(1);
name = rs.getString(2);
System.out.println("id = " + id + " Name = " + name);
}
}
} catch (Exception e) {
System.out.println("Problem" + e.toString());
} finally {
if (con != null) {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println(e.toString());
}
con = null;
}
}
}
This is my system
java version "1.7.0_01"
Java HotSpot(TM) 64-Bit Server VM (build 21.1-b02, mixed mode)
Ubuntu 11.10. OS type 64 bit
MySQL Version- MySQL 5.1.58-1ubuntu1
MySQL Client Version 5.1.58
Socket: /var/run/mysqld/mysqld.sock
I read the Q & A more then 15 in this site with same question, but that now one helped me. Please help me.
String url = "jdbc:mysql://localhost:3306/MyBusinessRecords";
Caused by: java.net.SocketException: Can't connect to SOCKS proxy:
a non-existant SOCKS proxy
bind-address = 127.0.0.1
You can try bind-address = 0.0.0.0 or jdbc:mysql://127.0.0.1:3306/MyBusinessRecords"
Try Java 1.6. I had a similar issue and changed back to Java 1.6 (I had upgraded to 1_7) and the issue went away. Probably need a different toplink or OracleDriver release for 1_7.

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.

ORA-12505 :TNS listener does not currently know of SID given in connect descriptor

I am using Oracle database. I've written a small JDBC connection program in Java but I am facing an issue with the listener.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcConnection {
public static void main(String[] args) throws SQLException,ClassNotFoundException {
String url = "jdbc:oracle:thin:#localhost:1521:orcl";
String user = "system";
String password = "password";
Connection connection = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(url, user, password);
if(connection!=null){
System.out.println("Success in connnection");
} else {
System.out.println("failure in connection ");
}
}
}
I am getting the following exception:
C:\Users\Administrator\Desktop>java JdbcConnection
Exception in thread "main" java.sql.SQLException: Listener refused the connectio
n with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
The Connection descriptor used by the client was:
localhost:1521:orcl
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java
:261)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:
441)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtensio
n.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at JdbcConnection.main(JdbcConnection.java:18)
This is the output of lsnrctl status
LSNRCTL for 64-bit Windows: Version 12.1.0.1.0 - Production on 16-JUN-2015 13:43
:41
Copyright (c) 1991, 2013, Oracle. All rights reserved.
Welcome to LSNRCTL, type "help" for information.
LSNRCTL> status
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for 64-bit Windows: Version 12.1.0.1.0 - Produ
ction
Start Date 16-JUN-2015 12:02:52
Uptime 0 days 1 hr. 40 min. 52 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File C:\app\orauser\product\12.1.0\dbhome_1\network\admin\l
istener.ora
Listener Log File C:\app\orauser\diag\tnslsnr\hydwemvm\listener\alert\lo
g.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC1521ipc)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=hydwemvm)(PORT=1521)))
Services Summary...
Service "CLRExtProc" has 1 instance(s).
Instance "CLRExtProc", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully
If you know your oracle database SID, then use
jdbc:oracle:thin:#localhost:1521:orcl
otherwise use below in case you have service name
jdbc:oracle:thin:#localhost:1521/orcl
Also, make sure service name with the name ORCL should be up and running. If still doesn't work, then you need to restart your machine and try again above.
Still, not working ? Then, try following :
Login with SYSTEM user and register LOCAL_LISTENER by running below SQLs.
alter system set local_listener = '(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))' scope = both;
alter system register;
How to check oracle SID and service name :
SELECT sys_context('USERENV', 'SID') FROM DUAL; -- It will return your oracle database SID
SELECT sys_context('USERENV', 'SERVICE_NAME') FROM DUAL; -- It will return your oracle database service name
If you want to know the default SID of your database use this query in sqlplus:
SELECT sys_context('USERENV', 'SID') FROM DUAL;
Use this value in the JDBC URL instead of "orcl".
Can you use the below URL?
Note the difference, this is to use the SERVICENAME instead of a SID.
jdbc:oracle:thin:#localhost:1521/orclservice
I am facing the same problem.
Try removing the LAN cable or disconnect your net connectivity and
restart the services of Listener and run the code.
It worked for me.

Categories