I am trying to write some Java code that connects to a remote database from my personal computer. I can currently ssh to these machines using a private/public key authorisation. I can access the GUI of these machines by creating SSH tunnels (with Putty).
I don't think the problems is with my code as I can create a DB using MySQL Workbench and can successfully query the db. When trying to access the db I use the same tunnell address that I use for the GUI. So my questions is down to how should I connect to the DB? Can anyone shed some light to my question? My code is posted below.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnector {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:mysql://localhost:9092/db";
//Database Username
String username = "root";
//Database Password
String password = "root";
//Query to Execute
String query = "select * from employee;";
//Load mysql jdbc driver
Class.forName("com.mysql.jdbc.Driver");
//Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl,username,password);
//Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs= stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()){
String myName = rs.getString(1);
String myAge = rs.getString(2);
System. out.println(myName+" "+myAge);
}
// closing DB Connection
con.close();
}
}
The error I get is:
Exception in thread "main" 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.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
This should probably be a comment, but my reputation doesnt allow for comments. I would venture to guess that the port on the server's network is blocking that port (whatever port you're using) but is allowing for ssh. What is this server/where/can you change the settings on any firewall to allow for connection?
If I get you right, the mysql is listening at port 9092 at the host you are connecting with ssh.
Then use this ssh command to connect:
ssh -L9092:localhost:9092 username#192.168.1.233
It creates a tcp listening socket at your local machine and tunnel any connections to port 9092 at local machine to the port 9092 at remote machine
Edit:
I missed that you are using putty. Then open connection settings dialog, then browse to ssh and find port forwarding. the notation is nearly the same: local port, to some ip:port at remote site: here you can find a step-by-step guide with screenshots
Related
I want to write a java application that uses a mysql database to store and retrieve information. I am still just a beginner and I do not have a lot of knowledge on web hosting providers and server architecture. In this application, several clients will have to access this remote database located on a server machine maybe.
Currently, I can connect to the database from the same computer that runs the mysql server (I am using workbench by the way). Any suggestions on what should I do?
public static Connection openDatabase()
{
Connection myConn;
try {
myConn =
DriverManager.getConnection(Configs.getProperty("DatabaseURL"));
return myConn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
The url is:
jdbc:mysql://Atomic-PC:3306/test?autoReconnect=true&rewriteBatchedStatements=true&useSSL=false&user=root&password=password
First of all you have to find connection URL, port and credential from MySql workbench you are using. If hosting provider provides a public IP for DB server you should be able to access it from anywhere by using following code in Java.
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String[] argv) throws Exception {
String driver = "com.mysql.jdbc.Driver";
String connection = "jdbc:mysql://localhost:3306/YourDBName";
String user = "root";
String password = "root";
Class.forName(driver);
Connection con = DriverManager.getConnection(connection, user, password);
if (!con.isClosed()) {
con.close();
}
}
}
For this reason you have to import mysql connection driver to your application first.
If you are trying to connect to remote database then yo need to change the database url from localhost to remote server ip address.
jdbc:mysql://Atomic-PC:3306/test
to
jdbc:mysql://<db-server-ip-address>:<db-server-port>/<db-name>
Assuming, remote server ip address is 10.234.05.123 and database port number is 3300 and database name is remoteDB. Then,
jdbc:mysql://10.234.05.123:3300/remoteDB
your web hosting company should be able to provide you with the url:port which you can use in your connection string to connect to MySQL(or any other remote db for that matter)
hello i am trying to connect my application to online database using the following code
import javax.swing.*;
import java.sql.*;
public class javacon {
Connection con = null;
private static final String url ="jdbc:mysql:\\sql204.byethost9.com:3306\\";
private static final String dbName = "b9_16134488_db";
private static final String userName = "b9_16134488";
private static final String password = "123.321";
public static Connection connectDB(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://sql204.byethost9.com:3306/b9_16134488_db/",userName,password);
JOptionPane.showMessageDialog(null, "connection is succseful");
return con;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
but i am getting error says the driver has not received any packet
from the server
i found one answer this one says i have to go to my cpanel in my host and add my ip address there but i need every user to be connect to the database to login and logout
Mysql database has file my.cnf where bind-address might be specified. If that is not there, then mysql bind itself to all interfaces, otherwise only to specified one. More about this Bind-address
Also I guess user must have permissions to connect to database. 'user'#'ipaddress'. And more you can read here Connection access
Your code seems fine, your problem probably is related with your MySQL database not allowing connections from your host. The easiest way to find if this is the problem is trying to connect to the database from the same machine with the same credentials with MySQL Workbench.
There are three main things that can block your MySQL from receiving external connections:
1) Configuration
Edit my.cnf removing the following line:
bind-address = 127.0.0.1
2) User Host
In MySQL all users have defined from which host the connection can home from. 'user'#'%' would allow you to connect from any host.
3) Firewall
Make sure that the port 3306 is open.
I have created MySQL database for my website using cPanel and phpMyAdmin on remote host and now i want to connect to this database my simple java program.I try this code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Main {
public static void main(String[] args) {
try{
Connection con=DriverManager.getConnection("jdbc:mysql://sfg.ge/sfgge_mysql", "my_username", "my_password");
Statement state=(Statement) con.createStatement();
String name="shota";
int id=3;
String insert = "INSERT INTO student VALUES ("+ id +",'"+ name +"')";
state.executeUpdate(insert);
}
catch(Exception ex){
}
}
}
In this code
DriverManager.getConnection(String url, username, pass)
SQLException throws such error:
null, message from server:
"Host '188.129.228.176' is not allowed to connect to this MySQL server"
Any suggestions appreciated.
Add new account:
'user1'#'exact_host' - host is specified
CREATE USER 'user1'#'exact_host'
or
'user1'#'%' - for any host.
CREATE USER 'user1'#'%'
Grant privileges you need and connect with new account.
Also look at this:
Make sure that the server has not been configured to ignore network connections or (if you are attempting to connect remotely) that it has not been configured to listen only locally on its network interfaces. If the server was started with --skip-networking, it will not accept TCP/IP connections at all. If the server was started with --bind-address=127.0.0.1, it will listen for TCP/IP connections only locally on the loopback interface and will not accept remote connections
I am trying to connect to a MySQL Server using JDBC tool in java (using eclipse). I was just wondering how to enter 2 user/password combinations. The first one is the one I use to connect to the server(for example when I ssh into the server) and the second one I enter into phpmyadmin. As of now, I am putting in the phpmyadmin password only into the jdbc connection properties and it's not connecting. This is my current statement:
conn = DriverManager.getConnection("jdbc:mysql://[IP of server]:3306/[Database Table name]", "[UserName (same as phpmyadmin)]","[Password (same as phpmyadmin)]");
I am getting a
java.sql.SQLException: null, message from server: "Host '[My computer's full host name]' is not allowed to connect to this MySQL server"
I was just wondering if I needed to enter my server login/password (the one I use for ssh) as well in addition to the phpmyadmin username/pwd. I am new to JDBC and MySQL server, so I would appreciate any tips.
Just for background, I am able to connect successfully through ssh and I can login to the server through phpmyadmin.
Here's how you can create an account that can access your server from another client machine:
CREATE USER 'bobby'#'localhost' IDENTIFIED BY 'some_password';
That creates the user, and says he can connect from localhost.
If he is on the machine 192.168.0.5, you'd do something like this:
CREATE USER 'bobby'#'192.168.0.5' IDENTIFIED BY 'some_password';
Then of course, you have to grant privileges appropriately:
GRANT ALL PRIVILEGES ON databasename.* TO 'bobby'#'localhost' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON databasename.* TO 'bobby'#'192.168.0.5' WITH GRANT OPTION;
That's been my experience anyway.
You're probably better off reading this section on how to specify MySQL accounts.
When you log in from PHPMyAdmin, the web server is located on the same server that hosts the Mysql database (in your case). Mysql, by default, does not allow connections from remote hosts; only the local machine may access the database.
I'll take a shot in the dark and say that the computer you're running the java code on is not the same machine that is hosting the mysql server. You must configure Mysql to allow connections from remote hosts via the config file and then change the Host row of the mysql.users table for the specified user to allow connection from your IP address (or, if security isn't your concern, any IP address.)
To configure mysql to allow connections from remote hosts you must remove the "bind-address=" line from the configuration file.
To allow any host to log on to a specific mysql user, you must set the mysql.users Host` column to "%".
Both of these must be done.
public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
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 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/"