How to access the remote database using java - java

Iam trying to access database from system to other system, below is code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class testConnection {
/**
* #param args
* #throws SQLException
*/
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
String connectionURL = "jdbc:sqlserver://xxx.xxx.xx.xx:1433;DatabaseName=fingerprintdb;user=sa;password=test";
// Change the connection string according to your db, ip, username and password
Connection con = null;
try {
// Load the Driver class.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// If you are using any other database then load the right driver here.
//Create the connection using the static getConnection method
con = DriverManager.getConnection (connectionURL);
//Create a Statement class to execute the SQL statement
Statement stmt = con.createStatement();
//Execute the SQL statement and get the results in a Resultset
ResultSet rs = stmt.executeQuery("select moviename, releasedate from movies");
// Iterate through the ResultSet, displaying two values
// for each row using the getString method
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate"));
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the connection
con.close();
}
}
}
Below is exception iam getting.
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host xxx.xxx.xx.xx, port 1433 has failed. Error: "connect timed out. 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:170)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1049)
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(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at testConnection.main(testConnection.java:26)
Exception in thread "main" java.lang.NullPointerException
at testConnection.main(testConnection.java:48)
Iam able to connect to the database from the same syste. but now iam trying to connect remote way.
I got the above ip address from typing ipconfig in cmd prompt.
Am I doing correctly, if not please correct me.
Below is log of pings to host.
Pinging xxx.xxx.xx.xx with 32 bytes of data:
Reply from xxx.xxx.xx.xx: TTL expired in transit.
Reply from xxx.xxx.xx.xx: TTL expired in transit.
Reply from xxx.xxx.xx.xx: TTL expired in transit.
Reply from xxx.xxx.xx.xx: TTL expired in transit.
Ping statistics for xxx.xxx.xx.xx:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

Yes, Sometimes it Happens.. (Do the following Process where your SQLServer is installed)
You need to Go to
Start > Microsoft SQL Server > Configuration Tools > SQL Server Configuration Manager
When it opens Go to
SQL Server Configuration Manager > SQL Server Network Configuration > Protocols for SQLExpress
Where you'll find the Protocol TCP/IP, if disabled then Enable it Click on TCP/IP, You'll find its properties.
In this properties Remove All the TCP Dynamic Ports and Add value of 1433 to all TCP Port
and restart your
SQL Server Services > SQL Server
And Its Done...

you need to configure the remote SQL server to accept TCP/IP connection and you may require to allow remote connection in case if it not enabled.

Related

MS SQL Connection: Android Studio never connects vs Eclipse IDE does

I am creating a program for a local organization to take inventory. App connects to SQL Server via MSSQL 8.2 connector. App on phone should allow for receiving and sending item information. I have a static class to connect to the database, that handles the connection. In Eclipse, I am able to successfully connect and query the database. In Android studio, I get errors on every attempt to connect.
-Server is hosted on same pc.
-Ports have been configured, repeatedly. Currently have inbound and outbound rules for TCP and UDP fully open. Dynamic ports are on for SQL server. Services for SQL server have been restarted dozens of times. 1433 has been enabled and toggled off, but are currently blank.
-Attempted to connect by IP address, host cannot be resolved
-Permissions edited to allow login access to modify the database
-Integrated security and TLS security tried at different times, both failed.
List of errors:
Connection to the host BLACK-G, "xxxxx" port 1433, has failed.
TCP/IP connection to the host failed, unable to resolve host.
Connection to the host named BLACK-G instance sqlexpress failed,No
address associated with hostname, open up UDP traffic to port 1434
Unknown host exception. Unable to resolve host BLACK-G
Connection Refused
Failed to connect
Connection to the host 192.168.1.219 has failed. Failed to connect to
192.168.1.219 (port 1433) from 192.168.1.87(port 33654) after 2478ms Verify connection properties.
Here is the code
package com.example.ccupboard_1;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseJAVA {
// #RequiresApi(api = Build.VERSION_CODES.KITKAT)//public static void main(String[] args) {
public static String Connect() {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://BLACK-G\\SQLEXPRESS;user=ay7;password=343434;databaseName=ayTestDatabase2;" ;
ResultSet resultSet = null;
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT Fname, Lname from dbo.Customers";
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
result += (resultSet.getString("Fname") + " " + resultSet.getString("Lname")+"\n");
}
} catch (SQLException e) {
e.printStackTrace();
result = e + "";
}
return result;
}
}
Snippet from main activity that calls connect method:
case R.id.buttonSignOut: { //used to test connection currently, simply attempts to connect and //returns the value to a textview on the page
Thread thread = new Thread() {
public void run() {
textviewLowItemAlert.setText(DatabaseJAVA.Connect());
}
};
thread.start();
break;
What would be the next step in resolving this issue? It works in Eclipse, but not in studio. I've tried more than a dozen different connection Strings, and most of them threw the same errors. Does my server not allow access to Android Studio? Most of the errors seem to be Android studio being incapable of locating it on the server.
Here's a snippet from a working app of mine where I can connect succesfully to a local ms sql.
In a config file I set the connection info.
public static String dbUser = "user";
public static String dbPassword = "password";
public final static String sqlString = "jdbc:jtds:sqlserver://ip:port//INSTANCENAME";
Then I start the connection like this.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
DriverManager.setLoginTimeout(5);
connection = DriverManager.getConnection(Config.sqlString, Config.dbUser, Config.dbPassword); // Connect to database
if (connection == null) {
ConnectionResult = "Verify Internet Connection";
Toast.makeText(activity, ConnectionResult, Toast.LENGTH_LONG).show();
Finally just do the query and close the connection.
Alright, was finally able to figure it out, with the JDBC-JTDS connector mentioned by JoaquinAlvarez.
Here's what happened:
-Used the connection info he provided, with my IP address, and a higher timeout
-Network Error IOException, EHOSTUNREACH(No route to host),
-Router changed my IP address, so had to fix that
-After that, I used my PCNAME\SQLEXPRESS for the the for the instance
-It returned Instance Unreachable, so I changed to SQLEXPRESS alone
-Then it returned DB Closed connection
-I looked at Windows Event Viewer, and it said:
"Encryption is required to connect to this server but the client library does not support encryption; the connection has been closed. Please upgrade your client library."
-I checked the SQL server in SQL SERVER Configuration Manager... Force Encryption was turned on.
-Tried again, and the JTDS connector finally connected to the Database and I was able to do things. No help with the MSSQL one yet though.
Thank you Mr. Alvarez!

Connection refused: connect, can't connect database mysql

I can't connect remote database. When I connect my own database on localhost, it connects. What's wrong?
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Caused by: java.net.ConnectException: Connection refused: connect
Java Code:
String url = "jdbc:mysql://ipadress:3306/database?autoReconnect=true&useSSL=false";
String username = "username";
String password = "password";
String query = "SELECT * FROM database";
System.out.println("Connecting database...");
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
//Uruchamiamy zapytanie do bazy danych
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
}
connection.close();
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
I can login to database on PHPMyAdmin, I have no root account, it's my friend's database. I checked if port 3306 is open here: http://www.yougetsignal.com/tools/open-ports/ and it's closed. Where can I open it? In router settings in "port forwarding"? What private IP and type(TCP or UDP) should I set to open this port?
(Apologies if this answer is incomplete, but there is too much that does not fit in comments)
1) Don't ignore exceptions. This is bad : with // handle the error and nothing else in your catch block, in case of error there, your code will not report the error, and will move on with the execution (it should exit/break/return, depending on where that piece of code is).
2) I think checking "SHOW GLOBAL VARIABLES LIKE 'PORT';" is not enough. Ask your friend if the database daemon actually listens to port 3306 on a network interface that you can reach. MySQL can be configured with networking disabled (skip-networking), or enabled but only for local machine (bind-address=127.0.0.1 or localhost -- it should be bind-address=0.0.0.0 or bind-address=hostname or public IP address...).
To check for that yourself, if you are on linux, try with nc or telnet (install nc if you don't have it): nc remotehost 3306. If you get "connection refused", the error is definitely not in your java code, but in the server setup.

SQLException while connecting to Azure SQL Data Warehouse using JDBC

I am trying to connect to Azure SQL Data Warehouse through JDBC. I am getting the following exception.
*
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host tcsqldatawh.database.windows.net, port 1433 has failed. Error: "null. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:242)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2280)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:493)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1387)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1068)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:904)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:451)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1014)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at testsqldw.SQLDatabaseConnection.main(SQLDatabaseConnection.java:30)
*
I have seen similar questions asked about connecting to the SQLServer DB here.
I configured the database to allow access to my IP using the process here.
Please check the code below:
package testsqldw;
import java.sql.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://databaseserver.database.windows.net:1433;"
+"database=databaseserver;"
+"user=username#databaseserver;"
+ "password=password;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
System.out.println("Total connection string is---\n"+connectionString);
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String createSql = "create table employee(employee_id varchar(20));";
statement = connection.createStatement();
boolean status=statement.execute(createSql);
System.out.println(status);
// Print results from select statement
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the connections after the data has been handled.
if (statement != null) try { statement.close(); } catch(Exception e) {}
if (connection != null) try { connection.close(); } catch(Exception e) {}
}
}
}
Total connection string is
jdbc:sqlserver://databaseserver.database.windows.net:1433;database=databaseserver;user=username#databaseserver;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
Please help me in resolving the issue.
Per my experience, the issue may be caused by the following reasons:
The SQL Server which you have created may not work fine.
You may use incorrect JDBC connection string.
For the first reason, you could use some client tools to connect to the SQL server. If you could connect to the server, that indicates the SQL server is ok.
If not ,you could create a new SQL Server. After then, you could create a new SQL Data Warehouse according to this URL https://azure.microsoft.com/en-us/documentation/articles/sql-data-warehouse-get-started-provision/.
The URL also includes the firewall config method.
I use the SQL Server InTouch to connect to the SQL Server. The followings are some description images.
You could get the parameters by the Azure Portal. The port number is 1433.
The following picture indicates that your server is ok.
For the second reason, you could copy the connection string from the azure portal and modify the password only.
Hope it helps. Any concerns, please feel free to let me know.

Can not connect to ms sql server using windows authentication on remote system

I was trying to connect to ms sql server 2008 which is installed on a remote system.But it showing error.The following is the way i had tried
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class mssql {
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection=DriverManager.getConnection("jdbc:sqlserver://192.168.1.220:1433;databaseName=sales;integratedSecurity=true;");
if(!(connection==null))
{
System.out.println("connected");
}
//
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is the error i am getting
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host 192.168.1.220, port 1433 has failed. Error: "connect timed out. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
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 mssql.main(mssql.java:14)
Any solutions for this problem
Is the 2008 SQL instance configured to be listening for TCP connections?
Start, Microsoft SQL Server 2008, Configuration Tools, SQL Server Configuration Manager
SQL Server Network Configuration
Protocols for [instance name]
There should be four items listed:
Shared Memory
Named Pipes
TCP/IP
VIA
For your environment, which should be enabled and which should be disabled? Most setups call for Shared Memory and TCP/IP enabled, the others disabled.
Try to connect from the command line:
sqlcmd -S 192.168.1.220 -E
Also, check this:
Is the server firewall configured (allow port 1433 or sqlservr.exe);
Is your instance name correct? If you are using SQL Server express, the server name would be 192.168.1.220\sqlexpress;
Are TCP connections enabled for the server (see answer from jdev);
Are remote connections enabled for the server (can be changed in SQL Server Management Studio, Server properties, Connections);
Is port 1433 correct? By default, only unnamed instances use static port 1433. Other instances use a dynamic port and require SQL Server Browser for discovery.
public class mssql {
public static void main(String[] args) {
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); modify
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
Connection connection=DriverManager.getConnection("jdbc:sqlserver://192.168.1.220:1433;databaseName=sales;integratedSecurity=true;");
if(!(connection==null))
{
System.out.println("connected");
}
//
} catch (Exception e) {
e.printStackTrace();
}
}
}
Then you look at this post:
JDBC: Simple MSSql connection example not working
-first enable your sql server to receive tcp connection from configuration manager.
-add sqljdbc library to project.
- add the .dll file of the library as vm argument ex: -Djava.library.path=......
-use the code below as example:
String connectionUrl = "jdbc:sqlserver://localhost;" +
"databaseName=Timesheet;integratedSecurity=true;";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "select top 100 * from paycal";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
int i =0;
while (rs.next()) {
jTable1.setValueAt(rs.getString("dayname"), i, 0);
jTable1.setValueAt(rs.getString("dater"), i, 1);
i++;
}

Unable to establish database connection to SQL Server 2008 using java in Eclipse IDE

I am trying to connect to HP Operations Manager Database using Java code in Eclipse IDE.
I am able to connect successfully through Microsoft SQL Server Management Studio 2008 but it fails through code.
I have installed "Microsoft JDBC Driver 4.0 for SQL Server"
Code:
import java.sql.*;
public class ConnectDatabase {
Connection dbConnection = null;
String dbName = "openview";
String serverip="10.105.219.102";
String serverport="1433";
String url = "jdbc:sqlserver://"+serverip+"\\OVOPS;databaseName="+dbName+"";
String userName = "HPOM-QA-WIN\\Administrator";
String password = "Nbv12345";
final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Statement statement = null;
ResultSet rs = null;
int updateQuery = 0;
public Connection getConnection() {
System.out.println(url);
try{
Class.forName(driverName).newInstance();
dbConnection = DriverManager.getConnection(url,userName,password);
System.out.println(DriverManager.getDrivers());
statement = dbConnection.createStatement();
String QueryString = "select Id from openview.dbo.OV_MS_Message where OriginalServiceId like '{FaultDn[1]}'";
updateQuery = statement.executeUpdate(QueryString);
if(updateQuery!=0){
System.out.println("success" + updateQuery);
}
statement.close();
dbConnection.close();
}catch (Exception e){
e.printStackTrace();
}
return dbConnection;
}
public static void main(String[] args) {
ConnectDatabase cDB = new ConnectDatabase();
cDB.getConnection();
}
}
I get the following error when I execute this code:
jdbc:sqlserver://10.105.219.102\OVOPS;databaseName=openview com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host 10.105.219.102, named instance ovops 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.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.getInstancePort(SQLServerConnection.java:3589)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.primaryPermissionCheck(SQLServerConnection.java:1225)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:972)
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.ucs.test.ConnectDatabase.getConnection(ConnectDatabase.java:27)
at com.ucs.test.ConnectDatabase.main(ConnectDatabase.java:51)
When I change the url to
String url = "jdbc:sqlserver://"+serverip+"\\OVOPS:"+serverport+";databaseName="+dbName+"";
I get the below error:
jdbc:sqlserver://10.105.219.102\OVOPS:1433;databaseName=openview com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'HPOM-QA-WIN\Administrator'. ClientConnectionId:f1d323b7-9998-418c-b2a2-f2a7bd7b9b04
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.ucs.test.ConnectDatabase.getConnection(ConnectDatabase.java:27)
at com.ucs.test.ConnectDatabase.main(ConnectDatabase.java:51)
I have explicitly added an inbound rule in windows firewall to allow UPD traffic on 1434 port, then disabled the firewall. But I still get this error.
The credentials provided here are used for connection using Microsoft SQL Server Management Studio and it works perfectly fine. But it fails through the code.
I am not sure where I am going wrong. I am unable to establish a successful connection through the code. Please help me.
Hey Thanks all for your responses. Finally I was able to resolve the issue. The problem was with the url and auth dll. Changed the url to
"jdbc:sqlserver://10.105.219.102:1433;instance=OVOPS;DatabaseName=openview;integratedSecurity=true"
and added the location of "sqljdbc_auth.dll" in java.library.path. It worked!
Thanks again for your efforts to help me :)
It took me a while to sort this issue out, but you have to head into the SQL Server Configuration Manager application. When that's loaded, expand the [SQL Native Client 11.0 Configuration] > Client Protocols.
Enable all three (Shared Memory, TCP/IP, and Named Pipes), if they aren't already.
Then click on TCP/IP and ensure that the default port is 1433.
If you have a 32bit system or version of SQL Server installed, do the same in the SQL Native Client 11.0 Configuration (32it) menu, enabling Shared Memory, TCP/IP, and Named Pipes and setting the default port to 1433.
Then click open the [SQL Server Network Configuration] or (32bit if applicable), and select the [Protocols for "YOURSERVERNAME"].
Ensure again that Shared Memory, TCP/IP, and Named Pipes are all enabled.
Then click on the [TCP/IP] Protocol Name, then select the [IP Addresses] tab at the top of the new popup window. For IP1 ensure that Active is YES; Enabled is YES (this is No by default, even if it is Active); and set the TCP Port to 1433 (tbh I don't know if you have to do this step, but I did and it worked!!); my TCP Dynamic Ports are set to 0 and I didn't change any of the IP addresses;
I did the same thing for IP10, which has IP: 127.0.0.1, which is the local machine.
I also scrolled down to the bottom of the page, and set IPAll TCP Ports to 1433, (dynamic ports is 49163).
Then you need to Apply all changes, close the properties window, and click on SQL Server Services in SQL Server Configuration Manager, and restart all running Servers.
This should do it :D
Catch example:
String url = "jdbc:sqlserver://localhost:1433/databaseName";
String username = "user";
String password = "pass";
Connection connection = DriverManager.getConnection(url, username, password);
1433 is default port.
Dont use '\' in url.
This is probably not an answer to your question, but I hope this will help you. Here is the way how to properly return connection (mysql):
import java.sql.*;
public class ConnectToDatabase{
public Connection getConn(){
final String DBPATH="jdbc:mysql://localhost:3306/mydb";
final String DBUSER="root";
final String DBPASS="";
Connection conn=null;
try {
conn = DriverManager.getConnection(DBPATH,DBUSER,DBPASS);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
Try changing your database user password. Make sure new password doesn't have special characters.
I faced same problem and it got resolved after changing the db password.
Steps of my workaround:
I was getting sqlserverexception.java 190 error stating unable to connect to host port: 4500 which was my localhost port.
Opened Sql Server Configuration Manager -> SQL Server Network Configuration -> Protocols for MSSQLSERVER -> Enabled TCP/IP.
Checked TCP port number. It was 1433. So I changed 4500 to 1433 in my registry file.
After following above steps, I got a different error this time startingpassword for my db user(sql-test) is incorrect. I changed the password to sqltest123 and it worked.

Categories