Can connect to MySQL db with java but not with PHP? - java

I have a java application, that can connect to an online MySQL database, like this:
private String hostName = "db4free.net:3306";
private String dbName = "mydbname";
private String username = "name";
private String password = "pw";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + hostName + "/" + dbName, username, password);
System.out.println("Connection established!");
} catch (Exception ex) {
ex.printStackTrace();
}
It works perfectly. However, I try the same with PHP (ignore hostname difference, this should be it):
$host = "85.10.205.173";
$dbname = "dbname";
$username = "name";
$password = "pw";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
// Open connection with db
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// Just an error message, if connection fails
die("Failed to connect to the database: " . $ex->getMessage());
}
And after a while, I get this: SQLSTATE[HY000] [2003] Can't connect to MySQL server on '85.10.205.173' (4)
So why do the two work differently? I think that remote access is enabled (because I could connect with java).

Disable the DNS hostname lookups in mysql
To disable DNS host name lookups, start the server with the --skip-name-resolve option. In this case, the server uses only IP addresses and not host names to match connecting hosts to rows in the MySQL grant tables. Only accounts specified in those tables using IP addresses can be used.
Don't forget to restart MySQL to take effect.
Not sure this will solve your problem.

Related

Connect to oracle database, knowing only the database name

I have an existing connection in R, where I use DBI library to do the following:
con <- dbConnect(drv, username = "user", password = "pass", dbname = "mydatabase.world")
This creates the following connection:
User name: user
Connect string: mydatabase.world
Server version: 11.2.0.4.0
Server type: Oracle RDBMS
Results processed: 0
OCI prefetch: FALSE
Bulk read: 25
Statement cache size: 0
LOB prefetch size: 1024
Open results: 0
I would like to do the same thing in Java. I browsed lots of tutorials, and arrived at this:
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
but I get this error:
The Network Adapter could not establish the connection
I could connect just with database name in R, how to do the same thing in Java?
My current DB_CONNECTION string is:
private static final String DB_CONNECTION = "jdbc:oracle:thin:#mydatabase.world";
tnsping:
Message 3511 not found; No message file for product=NETWORK, facility=TNSMessage
3512 not found; No message file for product=NETWORK, facility=TNSAttempting to
contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = tcp.world)(PROTOC
OL = TCP)(Host = 10.3.0.70)(Port = 1532))) (CONNECT_DATA = (SID = LUCAS)))
Message 3509 not found; No message file for product=NETWORK, facility=TNS'
Solution
For whatever reason, I could not use the database name in Java. Here is what I had to do:
Run tnsping (found in oracle directory, BIN subdirectory) with the database name as parameter
tnsping mydatabase.world
Then from there I got my host name and SID
The string is now:
String DB_CONNECTION = "jdbc:oracle:thin:#10.3.0.70:1532:LUCAS";
knowing only the database name
I don't really understand, according to your R code it seems to me that DB_USER = "user" and DB_PASSWORD = "pass".
Also did you try adding the port and the SID to your DB_CONNECTION String ?
private static final String DB_CONNECTION = "jdbc:oracle:thin:#10.3.0.70:1532:LUCAS";
I edited my post with your tnsping info.
If i understood corectly you are not sure about connection parameters as hosthame and port.
It seems that mydatabase.world is a dsn name. So parameters you needed can be located at dsn: /etc/odbc.ini or /etc/odbcinst.ini

How to connect to online mysql database from Java desktop app

I pave paid hosting, and i added my database to it. I am trying to connect to this online database from my java desktop application but, i got exception: Communications link failure.
here is my code:
public Kviz_DAO(){
try{
Class.forName("com.mysql.jdbc.Driver");
konekcija = DriverManager.getConnection("jdbc:mysql://penal.ba:2082/mydatabasename?"+
"user=mydbuser&password=mydbpassword");
}
catch(Exception ex){
ex.printStackTrace();
}
}
Can anyone tell me what i'm doing wrong.
Check that, if permission is in the DB server for your IP. If not then GRANT the permission for the IP
GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'#'%' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;
if not working, check the FIREWALL.
The default port for MySQL is 3306. Are you certain that the hostname and port you're using is correct?
Try this:
konekcija = DriverManager.getConnection("jdbc:mysql://penal.ba:2082/mydatabasename", mydbuser, mydbpassword);
Check this:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure
Can you connect using the MySQL admin?
sample code:
String url1 = "jdbc:mysql://localhost:3306/";
String db1 = "userdb";
String driver1 = "com.mysql.jdbc.Driver";
String user1 = "root";
String pass1 = "sarakrish";
try {
Class.forName(driver1).newInstance();
con = DriverManager.getConnection(url1 + db1, user1, pass1);
you should try this method:
String url = "jdbc:mysql://penal.ba:2082/";
String db = "mydatabasename";
String driver = "com.mysql.jdbc.Driver";
String user = "mydbuser";
String pass = "mydbpassword";
Class.forName("com.mysql.jdbc.Driver");
konekcija = DriverManager.getConnection(url+db,user,pass);
Download the connector J . Add it to your classpath and in the code:
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://remoteUri/database-name?"
+ "user=user&password=userpw");
Connection konekcija = DriverManager.getConnection("jdbc:mysql://penal.ba:2082/mydatabasename?" + "user=mydbuser&password=mydbpassword");
//konekcija should be an object of Connection class.....I think :-p
If you can't connect to a remote MySql database, this is due to permissions by the hosting company/server. You can solve this by adding permission for your ip.

com.mysql.jdbc.exceptions.MySQLSyntaxErrorException exception in CentOS server

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

communication link failure in java

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"

Access mysql data base from another system using java

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();
}
}

Categories