when i ll try to connecting mysql using jdbc means its succeessfully connected on localhost.but i replaced localhost by my ip address means itz not connected..y dis error is came..how it is cleared..help me.
dis is my coding:
package com.retrieve;
import java.sql.*;
public class retrieve{
public static void main(String[] args) {
System.out.println("Getting All Rows from a table!");
Connection con = null;
String url = "jdbc:mysql://192.168.1.249:3306/";
String db = "login";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM login");
System.out.println("username: " + "\t" + "password: ");
while (res.next()) {
String s = res.getString("username");
String s1 = res.getString("password");
System.out.println(s1 + "\t\t" + s);
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
The error is:
Getting All Rows from a table!
java.sql.SQLException: Data source rejected establishment of connection, message from server: "Host '192.168.1.249' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:650)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1808)
at com.mysql.jdbc.Connection.(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at com.retrieve.retrieve.main(retrieve.java:15)
With your MySQL server you need to add permission for your user to be able to access your db from the specified IP
Execute following query from mysql console
GRANT ALL ON YOUR_DB.* TO 'root'#'192.168.1.249';
create user 'login'#'192.168.1.249' on your mysql server.
mysql builds users from 'name' (here - login you specified) and 'host' (address from which user connects to server). You can use '%' char to describe 'all hosts'.
consider reading this section of docs:
http://dev.mysql.com/doc/refman/5.1/en/user-account-management.html
Try to close all the resources like Statment, ResultSet objects etc.Also, as #Jigar mentione, grant permission to the users as well.
Please check your port .If you changed your port number ,you got this error like
"com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"
Related
I'm a little new at that, but after starting my ec2 instance, and installing MySQL instance through RDS, I manage to connect to it through MySQL Workbench using ssh (.pem file).
My problem is I can't seem to have it right, when I'm trying to connect with jdbc, how exactly the authentication suppose to be done?
Here is my code, hope somebody can give me a hint on how to proceed:
public void create_table(){
Connection c = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");
// c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE USERS " +
"(ID INT PRIMARY KEY ," +
" DEVICE TEXT NOT NULL, " +
" NAME TEXT NOT NULL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
EDIT
I forgot few important details...
I wrote my code in Java using Jersey and servelt.
I Uploaded my WAR file to my ec2 instance.
Now after both web-app and MySQL server are running on the same instance, I want to build the communication..
Thank you!
Your SQL Syntax is incorrect. Text values are inserted as VARCHAR type in SQL. You can change the length of the text value depending on your need by changing the value with in the bracktes in VARCHAR(HERE). Try this code.
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE USERS " +
"(ID INTEGER not NULL," +
" DEVICE VARCHAR(255) not NULL," +
" NAME VARCHAR(255) not NULL,"+
"PRIMARY KEY (ID))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
how exactly the authentication suppose to be done?
you can use one of the form you use in your example but there are wrong things in both
c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");
you connect to localhost, if you have your test db on RDS you need to reference the end point of RDS like your second example
c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");
Here the end point will be correct but the string to connect is wrong. You can use the following form
String jdbcUrl = "jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test?user=root&password=password";
Connection con = DriverManager.getConnection(jdbcUrl);
or
String url = "jdbc:mysql://mydatabase.test.us-east-1.rds.amazonaws.com:3306/";
String userName = "root";
String password = "password";
String dbName = "test";
Connection connection = DriverManager.getConnection(url + dbName, userName, password);
To find precisely your database end-point, login to the RDS console (make sure to select the right region if not us-east-1), select your database and the Endpoint will be there
The other potential issue you might run is on Security Groups
The DB instance was created using a security group that does not authorize connections from the device or Amazon EC2 instance where the MySQL application or utility is running. If the DB instance was created in a VPC, it must have a VPC security group that authorizes the connections. If the DB instance was created outside of a VPC, it must have a DB security group that authorizes the connections.
Check your security group rules for both the RDS DB and the ec2 instance and make sure you can connect that the ec2 instance has access to RDS server
String name = "";
String port = "3306";
String user = "root";
String pass = "";
String dbname = "atm";
String host="192.168.5.219"; // my local host ip address
// I want to do this only with IP address..
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from atm";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString("name");
System.out.println("Name:" + name);
j.setText(""+name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
javax.swing.JOptionPane.showMessageDialog(null, e.getMessage());
System.out.println(e.getMessage());
}
When I run this I got an error:
error>> null, message from server: "Host 'DEEPAK-PC' is not allowed
to connect to this MySQL server"
Actually I want to make a program that takes data from another PC connected to my LAN network in school. So that's why I want to do this with IP address.
you have to first grant permission to access mysql from remote location
try this
GRANT ALL PRIVILEGES ON *.* TO 'root'#'192.168.5.219'
IDENTIFIED BY PASSWORD 'some_characters'
WITH GRANT OPTION;
FLUSH PRIVILEGES;
check this mysql site for more info
Running a java code in CentOS server to connect mysql
My code is -
String server = "", url = "", password = "", user = "", databasename = "";
Connection con = null;
try {
server = "xxx.xxx.xxx.xxx";
databasename = "xx";
user = "user";
password = "pass";
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://" + server + "/" + databasename + "";
con = DriverManager.getConnection(url, user, password);
System.out.println(server + " Database connection established");
System.out.println(con);
} catch (Exception e) {
System.out.println("***************connection failed********************");
e.printStackTrace();
}
My database is running in same server.
I am running this code in my local system and other server for same database and its running fine but its not running on same server where my database available.
I am getting this exception -
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '??????????????' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1027)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3361)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3295)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1852)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1975)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2470)
at com.mysql.jdbc.ConnectionImpl.configureClientCharacterSet(ConnectionImpl.java:1669)
at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3336)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1979)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:287)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at java.sql.DriverManager.getConnection(libgcj.so.10)
at java.sql.DriverManager.getConnection(libgcj.so.10)
at testthread.ConnectionFactory.getConnection(ConnectionFactory.java:28)
at testthread.ConnectionFactory.main(ConnectionFactory.java:39)
is any one help me what is the problem.
This problem seems to be very similar to the following:
Stumped SQL Exception for JDBC
Try checking character set configuration/data in your local database server
How to access the another system mysql database through java program?Am using the following program but i have get the communication error?what are the changes are need to connect the another system mysql database?
Public void dbconnection() {
String name = "";
String port = "3306";
String user = "system";
String pass = "system";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
You're not creating an instance of the driver class:
Class.forName("com.mysql.jdbc.Driver").newInstance();
[update: not necessary after all, ignore that]
And you're also referencing "sun.jdbc.odbc.JdbcOdbcDriver", is that necessary? If so, shouldn't you instantiate it also? [update: probably not]
If it works with localhost, and not with the IP specified, you need to configure mysql to listen on all ports.
jcomeau#intrepid:/tmp$ cat dbconnection.java; javac dbconnection.java; sudo java -cp .:/usr/share/maven-repo/mysql/mysql-connector-java/5.1.16/mysql-connector-java-5.1.16.jar dbconnection
import java.sql.*;
public class dbconnection {
public static void main(String args[]) {
String name = "";
String port = "3306";
String user = "root";
String pass = "";
String dbname = "imagetagging";
String host="127.0.0.1";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from taggers";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
URL:jdbc:mysql://127.0.0.1:3306/imagetagging
Name:1
Name:2
Name:3
Name:4
Name:5
Name:6
Name:7
Name:8
Name:9
Name:10
Name:11
Name:12
Name:13
Name:14
Name:15
Name:16
Name:17
Name:18
Name:19
Name:20
Name:21
As I understand you just need to specify another connection string, with another host and other credentials, e.g.:
...
String port = "3306";
String user = "user_name";
String pass = "password";
String dbname = "db_name";
String host="host_name";
...
You have to do 3(with 4th step optional) simple things to connect to your remote mysql database server.
Open up any GUI tool for mysql database management (your IDE, Mysql Workbench or smth else), check if you can connect to your database by specifying your credentials, host, port and database name.
If that succeeds you know there is nothing wrong on the db part (go to 3), if not, and you are sure you do everything correctly up to this point go to point 2.
check out this post on how to enable remote access to your db and try again (go to pkt 1)
You would have to clean up a bit your code, have a look into simple and to the point tutorial on how to connect and execute simple sql statements with java on Vogella tutorial
Once everything is working correctly, remember to give +1 on Vogella tutorial, praise the cybercity or any other website for the explanation on how to enable remote access on you db and don't forget to come back to stackoverflow and reward all good answers :)
I am working on a interface in java swing.we have four system connected with a lan.the interface is for accessing the database from the other system in the same local area network i used the following code to access the database by giving the ip address,database name,tablename but i could not connect the other systems database.how can i do this?
public void dbconnection() {
String name = "";
String port = "3306";
String user = "systech";
String pass = "systech";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
Use below code
public void dbconnection() {
String name = "";
String port = "3306";
String user = "systech";
String pass = "systech";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
Class.forName("com.mysql.jdbc.Driver").newInstance ();
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
System.out.println("Name:" + rs.getString(1));
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
Also, make sure to include jar file for connecting. You will get jar file here.
Update 1:
So, you have a
CommunicationsException: Communications link failure
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
Update 2
If your system is Windows, go to Start>>Run.
Type command. This will open command prompt.
Type "ping 192.168.1.61"
You might get reply in below format.
Pinging 192.168.1.61 [192.168.1.61] with 32 bytes of data:
Reply from 192.168.1.61: bytes=32 time=101ms TTL=124
If you don't get something in above format, then your MYSQL Server with ip 192.168.1.61 is NOT REACHABLE. Ask your team to start the server first. :(
If you have Linux version, open terminal and follow step 3.
Also check below link. Those might help you...
http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html
You should down load the jdbc driver and replace
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
by
Class.forName("com.mysql.jdbc.Driver");
If you still have issues asfter replacing Obdc stuff, please post the exception.
ALso check firewall settings and DB permissions.
If you'll get exception your app will not free system resources. This will work better:
} finally {
try {
rs.close();
st.close();
con.close();
} catch( Exception e ) {
e.printStackTrace();
}
}