I am new to google cloud, and I just configure all components needed in cloud computation. But I have a problem on MySQL connection between MySQL and APP engine/VM. I can browser see my main html page, but when my servlet try to make MySQL connection and it failed.
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://mysql external IP:3306/Database?user=us&password=pw");
Error message: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure and The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Class.forName("com.mysql.jdbc.GoogleDriver");
con = DriverManager.getConnection("jdbc:google:mysql://mysql external IP:3306/Database?user=us&password=pw");
Error message: java.lang.ClassNotFoundException: com.mysql.jdbc.GoogleDriver at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
I add appengine-web.xml in WEB-INF folder with true
Does anyone have the solution on this? I deploy to google cloud from my local Eclipse 2020-06 version.
Thanks
You an try this sample code:
String url = "jdbc:mysql://ip:3306/dbname?useSSL=false";
String user = "root";
String password = "password";
StringBuffer datStr = new StringBuffer("");
String query = "SELECT * FROM dbname.tablename";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
//Code
}
} catch (Exception ex) {
ex.printStackTrace();
}
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
I'm trying to create a connection to a database in my Java program. I'm not sure if i have the correct address for it though in my code.
Below is my connection code:
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "n1nlhdb5501-02.shr.prod.ams1.secureserver.net";
Connection conn = DriverManager.getConnection(url, "user1", "password");
return conn;
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
Unfortunately, Im really unsure of whether I have put the correct information into the url and the "Class.forname()" lines. I know the one is to load the actual driver and the other is the address of the database but i'm not sure if the information I have input is correct, because the connection is unsuccessful.
Is there anyway I could find the exact address that i need to use in the url string through an SQL statement maybe?
Also, I'm not sure if I'm loading the correct drivers for the jar file which i'm using, its called 'mysql-connector-java-5.1.35-bin.jar'
All help appreciated!
Thanks in advance
Marko
This is how you can connect MySQL database using Java.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://x.x.x.x:3306/databaseName", "username", "password");
Statement smt = con.createStatement(); //Create Statement to interact
ResultSet r = smt.executeQuery("select * from users where(AccountID='" + q + "');");
while (r.next()) {
name = r.getString("name");
}
con.close
} catch (Exception e) {
e.printStackTrace();
}
In your case URL will be like...
String URL = "jdbc:mysql://n1nlhdb5501-02.shr.prod.ams1.secureserver.net:3306/databaseName"
Edit:
It seems 3306 port is closed.
Nmap scan report for n1nlhdb5501-02.shr.prod.ams1.secureserver.net (37.148.204.135)
Host is up (0.075s latency).
Not shown: 97 filtered ports
PORT STATE SERVICE
80/tcp open http
443/tcp open https
3306/tcp closed mysql
I am trying to connect to Mysql from java
I am using Mysql 5.5 and I can access it remotely within the local network.But when I put that System on Static Ip I can't connect to Mysql remotely.
I able to connect to Mysql port and I already check for is firewall block that port but no such issue was found.
I also checked using Toad.
Any special setting need for that please help me..
Thanks in advance.
// Edited
Error Message
ERROR 2003 (HY000): Can't connect to MySQL server on 'Static_IP' (10061)
Hi can you please share stack trace of exception
Try Following solutions :
Make sure that MySQL Conncetor for java is included in your class path.
Try this sample code :
Declare class variables :
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://ip_address:port_name/db_name";
static final String USER = "username";
static final String PASS = "password";
Sample code to create database connection :
Connection conn = null;
Statement stmt = null;
// STEP 1: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 3: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM table_name";
ResultSet rs = stmt.executeQuery(sql);
Then iterate rs to fetch the rows
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
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"
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();
}
}