I want to make a connection to the remote database ssh, in my java program, so I write a java code for this, I can ssh to the database server from my code but I can't access to the database, this is my out put which contains the error :
(this link is my previous question link ,which is related to this question)
hi
identity added
session created.
session connected.....
shell channel connected....
connecting to database ...
db Method...
try-catch
Connecting to database...
DB_URL : jdbc:mysql://localhost:3366/DBNAME
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
com.mysql.jdbc.CommunicationsException
MESSAGE: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.io.EOFException
MESSAGE: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
STACKTRACE:
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1997)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:573)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1044)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2748)
at com.mysql.jdbc.Connection.<init>(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Main.connectToDB(Main.java:78)
at Main.main(Main.java:49)
** END NESTED EXCEPTION **
Last packet sent to the server was 0 ms ago.
STACKTRACE:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.io.EOFException
MESSAGE: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
STACKTRACE:
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1997)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:573)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1044)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2748)
at com.mysql.jdbc.Connection.<init>(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Main.connectToDB(Main.java:78)
at Main.main(Main.java:49)
** END NESTED EXCEPTION **
Last packet sent to the server was 0 ms ago.
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:641)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1044)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2748)
at com.mysql.jdbc.Connection.<init>(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Main.connectToDB(Main.java:78)
at Main.main(Main.java:49)
** END NESTED EXCEPTION **
Last packet sent to the server was 1 ms ago.
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(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Main.connectToDB(Main.java:78)
at Main.main(Main.java:49)
Goodbye!
done
I run this code
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class Main {
public static void main(String[] arg) {
try {
System.out.println("hi");
JSch jsch = new JSch();
String user = "***";
String host = "**.**.***.***";
int port = 22;
String privateKey = "id_rs";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
session.setPortForwardingL( 3366, host, 3306) ;
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
System.err.println("connecting to database ...");
connectToDB();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static String databaseName ="DBNAME";
static int lport = 3366;
static final String DB_URL = "jdbc:mysql://localhost:"+lport+"/"+databaseName;
static final String USER = "***";
static final String PASS = "***";
public static void connectToDB() {
System.out.println("db Method...");
Connection conn = null;
Statement stmt = null;
try{
System.out.println("try-catch");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
System.err.println("DB_URL : "+DB_URL);
System.err.println(USER+":"+PASS+";");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("hey!");
stmt = conn.createStatement();
String sql;
sql="SELECT * from Customer_Classes ; ";
ResultSet rs = stmt.executeQuery(sql);
try (BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"))) {
while(rs.next()){
String name = rs.getString("ID");
bw.write(name);
bw.newLine();
System.out.println(" name: " + name);
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
System.err.println("unable to close statement");
}
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
System.err.println("unable to close connection");
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
I define a user in remote server with all privilages
GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'#'IP' IDENTIFIED BY 'PASSWORD';
and add my Ip to bind-address in my.cnf (in DBserver)
what this errors means? and how can I fix it?
When connecting through portforwarding, the database will not see your original IP address, but the local one (localhost). So your grant should be GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'#'localhost' IDENTIFIED BY 'PASSWORD';
Mysql's bind-address parameter is for configuring the server IP, not the client IP. You should leave that setting (unless you otherwise need it) at its default, since you will be connecting from localhost anyway.
If Channel channel = session.openChannel("sftp");does what it seems to (i.e. connect you to the SFTP subsystem), sshd will probably not let you connect elsewhere. You should use Channel channel = session.openChannel("shell");
Check the server log.
Related
I am trying to connect to my database by JDBC on localhost. Connecting via windows authentication is no problem, but I want to connect via SQL authentication. Therefore, I created a login and a user corresponding to this login in my database. I can normally log in SSMS:
My connection string for JDBC:
jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123
Thrown exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'doszke'. ClientConnectionId:b7005fe3-904d-40c5-a89e-af0cb61250d6
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:254)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:258)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:104)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4772)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3581)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3541)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2395)
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/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251)
at main.Main.main(Main.java:38)
The username and password are the same, as those used for loging to SSMS.
Here my class code:
package main;
import java.sql.*;
public class Main {
private static ResultSet selectStan(Connection connection) throws SQLException {
String sql_stmt = "SELECT * FROM STAN;";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql_stmt);
System.out.println("Select executed");
return result;
}
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String userName = "doszke";
String password = "doszke123";
String url = "jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123";
try (Connection con = DriverManager.getConnection(url)) {
if(con != null){
System.out.println("connected");
} else {
System.out.println("unable to connect");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
As Mark Rotteveel pointed out, I was trying to connect to a LocalDB instance with JDBC, which seemed undoable. (ref: here)
However, I installed jTDS and added to my classpath, changed my connection string to
jdbc:jtds:sqlserver://./TestBazyDanych;instance=LOCALDB#EB7165FD;namedPipe=true
create a connection by the use of this connection string, username and password and it worked. The instance pipe number was taken from cmd line via
sqllocaldb i MSSQLLocalDB
There are few things need to check:
Did you create doszke user under the database and SSMS?
Are you able to login with doszke/doszke123 credentials in SSMS?
Please check 1433 port are open or not in your inbound and outbound firewall.
Trying to telnet on localhost 1433. If it's getting failed change below setting:
Go to Configuration tools -> SQL Server Configuration Manager Select SQL Server Network Configuration -> Select protocol in the right side window enable tcp/ip and restart the services in services.
I'm trying for the first time to JDBC to connect to a local database (Postgres) but I can't seem to actually made the connection. This is my code:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class JDBCExample {
public static void main(String[] argv) {
System.out.println("-------- PostgreSQL "
+ "JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/training", "iam47662285",
"MY56KZDZ");
} 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!");
}
}
}
And this is the error that appears when i try to execute it:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
Connection Failed! Check output console
Nov 02, 2017 4:36:52 PM org.postgresql.Driver connect
SEVERE: Connection error:
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "iam47662285"
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:438)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:222)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
at org.postgresql.Driver.makeConnection(Driver.java:450)
at org.postgresql.Driver.connect(Driver.java:252)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at UF2.Pruebas.BDR_BDOO.JDBCExample.main(JDBCExample.java:33)
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "iam47662285"
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:438)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:222)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
at org.postgresql.Driver.makeConnection(Driver.java:450)
at org.postgresql.Driver.connect(Driver.java:252)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at UF2.Pruebas.BDR_BDOO.JDBCExample.main(JDBCExample.java:33)
I use Fedora, but i don't know if that's relevant. Anyone have any idea of why is this happening?
Your username/password is incorrect in the following code:
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/training", "iam47662285",
"MY56KZDZ");
Manually log in to psql and verify what the correct username/password is. If necessary ALTER USER "xxxx" WITH PASSWORD ''; to a new one that you'll remember.
Also hardcoding login details is a very bad idea.
I'm making an app in android studio with connection to a SQL database server, I have a problem in connecting to the database.
Code:
import android.util.Log; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import net.sourceforge.jtds.jdbc.*;
Log.i("Android", " MySQL Connect Example.");
Connection conn = null;
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
//test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;
//String connString = "jdbc:jtds:sqlserver://localhost:1433/quehojaes;encrypt=false;user=Pc-PC;password=;instance=SQLEXPRESS;";
// String connString = "Data Source=localhost:1433;Initial Catalog=quehojaes;Integrated Security=True";
String connString ="jdbc:jtds:sqlserver://localhost:1433/quehojaes;";
String username = "Pc-PC";
String password = "";
conn = DriverManager.getConnection(connString);
Log.w("Connection", "open");
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("select * from planta where id=1");
//Print the data to the console
while (reset.next()) {
dato = reset.getString(3);
Log.w("Data:", reset.getString(3));
Log.w("Data",reset.getString(2));
}
conn.close();
} catch (Exception e) {
Log.w("Error connection", "" + e.getMessage());
}
return dato;
}
.................................
I got an error at line (conn = DriverManager.getConnection (connString)), so I guess it is wrong user I'm trying to get into the database, I enter Windows user authentication with a local database and I have no password for that user called Pc.
There are lines discussed by failed login attempts I've tried.
Thanks for the help!
localhost means your current machine. That would be the phone. Since SQLServer isn't running on your phone, its the wrong string. Use your PCs IP address, and make sure you can access that port through any ISP or personal firewalls.
As an aside- this is a HORRIBLE way to do things. You have to put your password the the SQL server in your app. Its trivial to decompile it and own your data. Instead you should put up a web service inbetween the two, so only machines you own on your local network need to have the db password.
My application runs on Linux Mandriva and can't get a connection to the MySQL database.
Part of my.cnf:
bind-address="127.0.0.1"
# skip- networking
I setted wait_timeout as follows:
SET GLOBAL wait_timeout = 28800;
I trying to get a connection to the database:
public class TestJdbc {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String driver = "com.mysql.jdbc.Driver";
String dbName = "gibrid", userName = "java",
password = "java";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName, userName, password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I packed this class in jar and send to the server. When I try to execute it, I get the following:
com.mysql.jdbc.CommunicationsException:
Communications link failure due to underlying exception:
** BEGIN MESSAGE **
java.net.ConnectException
MESSAGE: Connection timed out
STACKTRACE: java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:333)
...
But when I run this code from my localhost, everything is OK:
Connected to the database
Disconnected from database
What could be the problem?
Can you telnet to port 3306 on that Linux server ? That will tell you if something is listening on that port or not.
Note that if you run your code from your Windows server, the following line:
jdbc:mysql://localhost:3306/";
means you're connecting to a service on your Windows machine, not your Linux machine.
I am writing a java code to connect with MS SQL Server 2005. MS SQL Server is on Remote server windows server 2003. I am trying the following code but i am unable to establish a connection:
import java.*;
public class Connect {
private java.sql.Connection con = null;
private final String url = "jdbc:sqlserver://";
private final String serverName="xxx.xxx.xxx.xxx";
private final String portNumber = "1433";
private final String databaseName="myDb";
private final String userName ="user1";
private final String password = "xxxx";
private final String selectMethod = "cursor";
// Constructor
public Connect() {}
private String getConnectionUrl() {
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties() {
System.out.println("Perform Operations ");
}
private void closeConnection() {
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Connect myDbTest = new Connect();
// myDbTest.displayDbProperties();
}
}
But I am getting following exceptions:
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
Error Trace in getConnection() : The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect
Error: No active Connection
I am not getting where is the problem in the above code or do i need to do some setting
to connect to remote server.
Please give me your valuable suggestion which can help me to overcome with this problem.
Make sure that your SQL Server is configured to use TCP/IP. Enable it from SQL Server's Network Utility app. Also check there that the SQL Server is using port 1433 (IP Addresses - IPAll - TCP Port).
Try to use "telnet <server_host> 1433". If it doesn't connect you will not be able to establish a connection.
IMHO "Connection refused" means your database server is not visible from your application server.
Check IP address and port.
Check database connectivity directly from your database server (to avoid firewalls).
Check database connectivity from your application server.
Hope this will help you
ALLOW THE CONNECTION FIRST IN WHICH PC YOUR SQL SERVER IS RUNNING...
GO TO CONTROL PANEL-->ADMIN. TOOLS--->Windows Firewall with Advanced Security-->Inbounded rules-->new rule-->select port radio button -->next-->enter port 3306-->click next -->finally give the rule name like conn any...click finish