Can't connect to sql server with java - java

I'm trying to connect to a local sql server using Java and Microsoft SQL Server.
I'm using sql server auth.
Here's the code:
import java.sql.*;
public class Main {
public static void main(String[] args) {
String userName ="testlogin2";
String password ="pass";
String url ="jdbc:sqlserver://localhost/LabNoteMap;integratedSecurity=true;"; //LabNoteMap beeing target db
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("end");
}
}
and the stacktrace:
"C:\Program Files\Java\jdk-9\bin\java" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.5\lib\idea_rt.jar=63510:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.5\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\Deus\IdeaProjects\testMYSQL\out\production\testMYSQL;C:\Users\Deus\Desktop\jdbc\sqljdbc_6.0\enu\jre8\sqljdbc42.jar Main
end
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost/LabNoteMap, port 1433 has failed. Error: "localhost/LabNoteMap. 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:2369)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:551)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1963)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1628)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1459)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:773)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1168)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:678)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
at Main.main(Main.java:13)
Process finished with exit code 0
also some ss:
Also note that in Sql server configuration, the tcp/ip is enabled and the port is set to 1433.
I guess could be a firewall? but not sure how to check for it, or maybe something else?

Your connection string is wrong. You should change it
String url ="jdbc:sqlserver://localhost/LabNoteMap;integratedSecurity=true;";
to
String url ="jdbc:sqlserver://localhost;databaseName=LabNoteMap;integratedSecurity=true;";
You are not targeting the db which you want to establish connection.

private static String url="jdbc:sqlserver://localhost:1433;DatabaseName = students";
I'm using msbase.jar and mssqlserver.jar and msutil.jar, maybe you are using the wrong jar or your url is wrong (DatabaseName = ?)

Related

Java connection to sql server

Ok so I have this code:
package com.andrewxd.banksystem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Interface
{
public static void main(String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1443;user=Andrew;password=andrei23;database=BankSystem");
System.out.println("test");
Statement sta = conn.createStatement();
String Sql = "select * from Clients";
ResultSet rs = sta.executeQuery(Sql);
System.out.println(rs.next());
} catch (Exception e){
e.printStackTrace();
}
}
}
but it gives me this error can somebody help me?:
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1443 has failed. Error: "Connection refused: connect. 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.".
I've tried searching but I didn't really understand much.
from what i understand the port is incorrect but how do i find the correct ip/port?
1) Open SQL Server configuration manager and check to see if the TCP/IP under Network configuration protocols is enabled.
2) Under properties of the SQL serve under Connections check to see if Allow remote connections to this server is allowed.
3) Check to see if you can connect via SSMS and query the database.
4) In SQL Server Configuration manager check to see if the SQL Server Browser service is running. (this is not enabled by default nor is it set up to start up automatically by default).
5) If all those are set up then I would check the firewall.
(For anyone that might come across this the solution was to allow SQL Server and windows authentication)
Make sure your sql server configuration
-has TCP configured, and configured at that IP address.
You can test a couple things:
turn off Windows Firewall, from services.msc.
try connecting to SQL Server through the IP address,username,pwd the
application is trying to use. (open enterprise manager, connect, enter IP address etc)
Try using jtds driver for SQLServer.
Installing Oracle JDBC driver from Here
And with your code looking like this:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class OracleJDBC {
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:BankSystem", "Andrew","andrei23");
}
catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
It should probably work, if not, what does the output look like now ? Still equal to what it was before ? Did you check firewalls ? Connectivity to server allowed ?
The standard port for sqlserver is 1433 and not 1443 as far as I recall it right.

JDBC Connection works on Windows but does not work on Ubuntu

I have a really simple piece of JAVA code, where I try to connect from JAVA to my Oracle DB.
Everything works under Windows, but when I try to run it on Ubuntu, I have got an error.
I read a lot and I have tried lot of solutions. Here's my code:
package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class OracleJDBC {
private static String driver = "oracle.jdbc.driver.OracleDriver";
private static String password = "*****";
private static String dbname = "XE";
private static String username = "userir";
public Connection getConnection() {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:" + dbname, username,
password);
} catch (SQLException e) {
System.out.println("Connection Failed");
e.printStackTrace();
return null;
}
return connection;
}
public void closeConnection(Connection connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
when I run it, I receive an error:
Connection Failed java.sql.SQLRecoverableException: IO Error: The
Network Adapter could not establish the connection at
oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458) at
oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:546)
at oracle.jdbc.driver.T4CConnection.(T4CConnection.java:236)
at
oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521) at
java.sql.DriverManager.getConnection(DriverManager.java:571) at
java.sql.DriverManager.getConnection(DriverManager.java:215) at
utils.OracleJDBC.getConnection(OracleJDBC.java:26) at
utils.TestMain.main(TestMain.java:6) Caused by:
oracle.net.ns.NetException: The Network Adapter could not establish
the connection at
oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392) at
oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:434)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:687)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:247) at
oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1102) at
oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:320) ... 8
more Caused by: java.net.ConnectException: Connection refused at
java.net.PlainSocketImpl.socketConnect(Native Method) at
java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at
java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at
java.net.Socket.connect(Socket.java:579) at
oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:150) at
oracle.net.nt.ConnOption.connect(ConnOption.java:133) at
oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:370) ... 13 more
I logged in: sqlplus sys as sysdba
I started db: startup
I logged into Oracle as userir. XE exists.
I have no idea, what I did wrong...
Thank you in advance for your hints!
Verify your connection string.
I've experienced similar issues with various databases because I forgot to update localhost with the proper hostname.
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:" + dbname, username,
password);
Ensure that the connection string matches what you're specifying in sqlplus and you should be good.
Finding the connection string
Determining the connection string can be difficult, but being that you can connect via sqlplus it should be a bit easier:
My SqlPlus connection string looks like: sqlplus user/pass#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=hostname.network)(Port=1521))(CONNECT_DATA=(SID=remote_SID)))
If I bring this into Java it now looks like:
"jdbc:oracle:thin:user/pass#//hostname.network:1521/remote_SID";
Alternatively, if you connect via SQLDeveloper the string is made up on the connection properties:
now the hard part is if you truly are localhost and need to figure out the connection string from there.
First, try your IP address instead of localhost (In my screenshot, the 192.168.0.106) to make a string like:
"jdbc:oracle:thin:user/pass#//192.168.0.106:1521/remote_SID";
If that doesn't work, check your firewall, ensure that port 1521 is open (assuming you did not change the port setting, alter text accordingly if you did)
If still no resolution you will need to check out your listeners file. I'm going to link to some documentation if that's the case and kindly defer to some of the more senior Oracle/Linux guru's
http://docs.oracle.com/html/B10812_06/chapter5.htm - For 10g listener.ora information
http://docs.oracle.com/cd/E11882_01/network.112/e10835/listener.htm#NETRF008 - For 11g listener.ora information
http://docs.oracle.com/cd/E16655_01/network.121/e17610/listenercfg.htm#NETAG010 - For 12c listener.ora information
I'm guessing is that you've got some firewall or some network thingy blocking you from getting from your Linux box to your oracle server. Note the "connection refused" portion of the stacktrace..
...
java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at
...
Oracle listens on port 1521, no? Maybe shell on the linux box and see if you can just telnet to the oracle host of 1521
telnet localhost 1521
Did you get connection refused there as well? I'm guessing that the Linux box doesn't have port 1521 open for whatever reason (firewall or the oracle listener isn't running).
Also, are you sure its localhost that you want to connect to when you deploy to Linux or is the expectation that the Oracle server is on a different machine? If the Oracle server is on a different machine, that machine's name needs to be in the connection string and not "localhost".
Welcome to the worst part of JDBC; figuring out the freaking connection string.
The issue is with secure random gathering.
As per this SO Discussion, Oracle JDBC Driver tries to get a secure random from the OS that it uses as part of connection establishment with Oracle. The issue is that your OS (Ubuntu) doesn't have enough randoms to give back and blocks you till it secure your request (the request of Oracle JDBC Driver).
A solution would be to ask Oracle JDBC Driver to avoid blocking until getting the complete requested random and use whatever it found. To do so, you have to use -Djava.security.egd=file:///dev/urandom.
More details on the SO Discussion mentioned above.

Receiving SQLException "Login failed for user" connecting to SQL Server 2008

I am trying to connect to SQL Server 2008 via Java.
I've added sqljdbc4.jar to my project's library.
No username and password is set for database accessing the database (Windows Authentication).
The 1433 port is Listening, but I still receive this exception:
SQL Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ''. ClientConnectionId:085d5df3-ad69-49e1-ba32-b2b990c16a69
Relevant code:
public class DataBases
{
private Connection link;
private java.sql.Statement stmt;
public ResultSet rs;
public DataBases()
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=DB;";
Connection con = DriverManager.getConnection(connectionUrl);
}
catch (SQLException e)
{
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE)
{
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
}
If you want windows authentication you need to add the option integratedSecurity=true to your JDBC URL:
jdbc:sqlserver://localhost:1433;databaseName=DB;integratedSecurity=true
You also need sqljdbc_auth.dll (beware of 32/64 bit) in your Windows system path or in a directory defined through java.library.path
For details see the driver's manual: http://msdn.microsoft.com/en-us/library/ms378428.aspx#Connectingintegrated
I was having same issue when I tried to connect to Microsoft SQL server from Java. I used jTDS driver instead of regular SQLJdbdc Driver.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String connectionUrl = "jdbc:jtds:sqlserver://localhost:1433;databaseName=DB;integratedSecurity=true";
Connection con = DriverManager.getConnection(connectionUrl);
I had the same issue. Its because of the wrong format of the ConnectionUrl. You are missing username and password in the ConnectionUrl.
String ConnectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=DB","username","password");"
I hope it works well!!!
This post my help:
jdbc.SQLServerException: Login failed for user for any user
You need the integratedSecurity=true flag and make sure the server properties are indeed set to 'Windows Authentication Mode' under Security.

Having trouble connecting to mySQL server on linux server from netbeans/java

I am unable to connect to a MySQL server which is hosted on a linux server through netbeans.
All of these credentials work when connecting through MySQL Workbench "Standard TCP/IP through ssh".
Here is my code:
public class Database {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://john.myschool.edu:3306/cs3610";
private static final String USERNAME = "mbrooke";
private static final String PASSWORD = "mypass";
private Connection connection;
public Database() throws Exception{
try{
connect();
}catch(SQLException e){
if(connection !=null){
connection.close();
}
}
}
//Open connection to database
private void connect() throws Exception{
connection = null;
Class.forName (DRIVER).newInstance ();
connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
}
I am getting SQLException with #521 on the line that starts "connection = DriverManager..." and I'm not sure what is causing this problem. The driver seems to be installed correctly as, when stepping through, I make it past the "Class.forName(D..." line with no exceptions thrown.
It sounds like your Database server doesn't have port 3306 open, or your MySQL credentials aren't allowed to use remote connections.
MySQL Workbench's TCP/IP over SSH setting first opens an SSH connection to the SSH server, then connects to the database server (often localhost or 127.0.0.1). So the MySQL connection is actually initiated from the SSH server. So the ability to connect through that channel only demonstrates that your java code would work if it were running on the server into which you're SSHing. But you may still have a firewall or MySQL permissions issue when trying to run the code from another machine.
I would try downloading a MySQL client to your machine and seeing if you can connect using that method: mysql -h myDatabaseServer.school.edu cs3610 -u mbrooke -p'mypass' and see if that works. You'll likely either get a "connection not available" error or a "user mbrooke doesn't have permission to access remotely" which should give you some insight into which problem you're facing.
Try it without ending slash
URL = "jdbc:mysql://john.myschool.edu:3306/cs3610/";
like
URL = "jdbc:mysql://john.myschool.edu:3306/cs3610";
or you have a Database named "cs3610/"

General JDBC Setup

So I have a MySQL database set up on a Debian server and it works fine from a phpMyAdmin client. I'm currently working on a project to write a Java server that would be able to use the MySQL database that is already on this server through a JDBC connection. I've looked at many tutorials and documentations but all of them seem to just explain how to do client-side code, but I have yet to figure out how to even successfully open a JDBC connection to the server. As far as I am concerned, I believe that program has the drivers properly set up because it's not crashing anymore (I simply direct the Java Build Path of my program to the Connector/J provided by MySQL). As far as my program goes, this is what it looks like...
import java.sql.*;
public class JDBCTest {
public static void main(String[] args) {
System.out.println("Started!");
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
System.out.println("Driver registered. Connecting...");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "password");
System.out.println("Connected!");
conn.close();
} catch (SQLException e) {
System.out.println("Error!");
e.printStackTrace();
}
}
}
This is what's printed...
Started!
Driver registered. Connecting...
It's as if the DriverManager.getConnection(String) just freezes there. I'm sure this is a problem with the server because when I intentionally misspell localhost, or an IP address, the program crashes within 20 seconds. This just hangs there forever.
Sorry about this wall of text, but my final question is if anyone has any information what I should do or install on the server to get this to work? Thank you so much!
Try following:
public class MySqlDemo {
public static void main(String [] args) {
java.sql.Connection conn = null;
System.out.println("SQL Test");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?user=root&password=");
}
catch (Exception e) {
System.out.println(e);
System.exit(0);
}
System.out.println("Connection established");
}
You have to provide the name of the Schema to which you are connecting. Usually, the port is also added.
This is a sample connection string:
jdbc:mysql://repos.insttech.washington.edu:3306/johndoe?user=johndoe&password=jddb
3306 is the port and the first instance of johndoe is the name of the Schema. The second instance of johndoe is the username.
It could be that the Connector/J library is trying to use a named pipe to connect to the MySQL server rather than using TCP/IP and for some reason the named pipe isn't available. Try specifying a port number.
You may also want to try turning on some logging in Connector/J's configuration as described here.
Try putting port number and schema there
Try logging into database using some SQL client, may be SQL console
Try other drivers, may be some newer or perhaps older

Categories

Resources