Java JDBC Communications link failure after deploying online - java

I have created my first API using java httpServlet on netbeans. After days working I could finally connect it to this mySQL googleCloud database and get results locally. But once this API is published on google cloud using appengine, below error was thrown:
Error sqlException: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.
But the mySQL database is allowing access for all IPs, so what could be the problem? Below is my code:
public class HelloServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
//out.println("Dear vistor, you are accessing my first project deployed on cloud. Thank you");
try {
Class.forName("com.mysql.jdbc.Driver");
String url = String.format("jdbc:mysql://IP:3306/DatabaseName?useSSL=false&useUnicode=true&characterEncoding=UTF-8");
Connection connection = DriverManager.getConnection(url, "userName", "Password");
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("select test from tableTest;");
while (resultSet.next()) {
out.println(resultSet.getString(1));
}
}
} catch (ClassNotFoundException ex) {
out.println("Error ClassNotFoundException:" + ex.toString());
} catch (SQLException ex) {
out.println("Error sqlException:" + ex.toString());
}
catch(Exception ex){
out.println("Exception:" + ex.toString());
}
}
}
Update:
Based on this link, I have discovered that when publishing online I should not use a password. So I have updated my code to use jdbc google drive in this way:
Class.forName("com.mysql.jdbc.GoogleDriver");
String url = String.format("jdbc:google:mysql://appId:instanceId/dbName?user=root");
Connection connection = DriverManager.getConnection(url);
But when I published online , same error was thrown...
Update2:
Could it be bcause my appId contains "-" like "test-123"? But actually I am sending my url in this form:
url = "jdbc:google:mysql://test-123:myInstance/myDatabase?user=root&useUnicode=true&characterEncoding=UTF-8";

Related

Slow connection after connection to database with web-hosting

Heading ##I have problem with my java application with database in mySQL and swing GUI.
When I've used localhost everything worked properly. But now I would like to share project with my friend and we decided to use server hosting.
And here is a problem:
Now application works very slow, after pressing a button I have to wait a few seconds for the program to respond. Also the connection is lost from time to time. I have no idea where can I find reason for the problem... Do somebody now what is the reason of this problem?
private static Connection connection = null;
Boolean error = false;
private static String jdbcURL = "jdbc:mysql://host_name:3306/db_name";
private static String user = "user";
private static String password = "password";
MakeConnection(Connection connection) throws SQLException{
this.connection = connection;
try {
getConnection();
System.out.print("Connected to the data base in MakeConnection");
}
catch(Exception e) {
error = true;
System.out.print("Error in connection in MakeConnection consturctor" + e.getMessage());
}
finally{
if(connection!=null) connection.close();
if(error) System.out.print("Problem with connection");
else System.out.print("Program finished");
}
}
public Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL,user,password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
Also sometimes application shows this error:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I don't see any problem in your code. The problem is probably with your server hosting. You should check the country of the host provider and measure the time required to send a request to the server. Also you should use logger instead of System.out.println so you can examine required time for actions like db access, application logic and find a bottleneck.

Create connection to SQL database using JDBC Driver- SQLException [duplicate]

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.

Connecting MySQL Database to NetBeans Error

I have a problem when running my code in NetBeans in order to see if mySQL is connected. This is the code:
public static void main(String[] args) {
Connection connect = null;
try{
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}
}
}
when I run it prints out "RIP". When I debugged it line by line, it went from the "connect = DriverManager.getConnection..." to "System.out.println("RIP"), and when I look at the "Exception e" it says "e = (java.sql.SQLNonTransientConnectionException) java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near '=TRUE'."
Now, why is that?????
I think you need to add
Class.forName("com.mysql.jdbc.Driver"); .
Also, make sure everything in Connection conn = DriverManager.getConnection (String url, String user, String password); are set correctly.
From the url format in your code, it's like you are trying to get direct connect to specific table tUsers in your database. And I dont think that would work. Correct me if I'm wrong whether it's literally your database name or not.
Because the basic url format i know, should be like jdbc:mysql://localhost:3306/yourDBname .
If you already set the url correctly as is written in your post, then the code is
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}}}
Hope that could do the work.

Java connection to mySQL database

i have a database for practice at phpMyAdmin. i use XAMPP. I am in very early stages of learing about the conection with a database. I followa tutorial and i think i am understanding the concept and everything is cool. But i stepped on a problem that despite the fact that there are answers on the internet, i cant solve it. here is my code:
import java.sql.*;
public class DBConnect {
private Connection connection;
private Statement statement;
private ResultSet result;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:1234/practicedb"); //code stucks here and after some minutes it is throwing an exception
System.out.println("Connected");//this is never executed.
statement = connection.createStatement();
} catch (Exception ex) {
System.out.print("Error in Constractor: "+ex);
}
}
public void getData() {
try {
String query = "select * from cars";
result = statement.executeQuery(query);
while (result.next()) {
String name = result.getString("carName");
String id = result.getString("carID");
String modelNum = result.getString("modelNumber");
System.out.println("Car name: " + name + ", " + "Car ID: " + id + ", " + "Car model number: " + modelNum);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
In the main class i create an instance of the class and then call the getData().
The code stucks in that line:
connection = DriverManager.getConnection("jdbc:mysql://localhost:1234/practicedb");
And it throws that:
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.java.lang.NullPointerException
This similar question was answered here: answer
But the suggestions are poor. I have tried flushing dns. I checked the URL and this is the one i connect to the database on phpmyadmin. i changed localhost to my ip adress. but all those just dont work.
I would really appreciate help. Is the first step on managing to receive that knowledge and i actually cant proceed at the moment. Thank you :)
i noticed that if i change the localhost:1234 to a random one like localhost:5432 it is throwing the error immediatelly. But when i have it on 1234(which i the port i have choosen through xampp config) then the programm runs for round about 5 minutes before it got terminated with the exception
Usually MySQL listens on the default port 3306.
If your database is named practicedb then your code should look like this:
private Connection connection;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicedb");
System.out.println("Connected");
} catch (Exception ex) {
System.out.print("Error creating connection: "+ex);
}

Can't access MySQL Database After deploying to the Cloud - CommunicationsException

I connect to my Google Cloud SQL via my App Engine Java Rest API Project to retrieve and store data on my cloud. I can successfully communicate with the server via Localhost but after I publish, I get this error:
Trying to Run Query:
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.
While there's so many solutions out there, I'm sad to say none of them worked.
Here's my connection string:
String url = null;
try {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://APP_ENGINE_ID:SQL_INSTANCE_NAME/DB_NAME?user=root";
} else {
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://MY_IPV4_ADDRESS:3306/DB_NAME?user=root";
}
} catch (Exception e) {
e.printStackTrace();
}
I get this error via my Rest API after I publish it only. Basically, works via Localhost but not remotely on the cloud.
I debugged and pin pointed the place where it crashes. It happens after I try to establish a connection with the server and execute a query:
try {
//THIS is where it crashes
conn = DriverManager.getConnection(url);
try {
String query = "SELECT * FROM UserTable";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
//Code
}
st.close();
} finally {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
Has anyone faced this issue before?
Like Herman, Igor and Vadim pointed out, it was a simply error in my PROJECT_ID:INSTANCE_ID in this line:
Incorrect Code:
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://APP_ENGINE_ID:SQL_INSTANCE_NAME/DB_NAME?user=root";
}
I've been using my App engine ID instead of the Project ID, which I should have been using.
Corrected Code:
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://PROJECT_ID:SQL_INSTANCE_NAME/DB_NAME?user=root";
}
as You can see i have called using asyncTask in Android (same as Thread in java )
public class Connect extends AsyncTask<Context, Integer, Long>
{
protected Long doInBackground(Context... contexts) {
Connection connection;
String query = "Some query";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://<your cloud IP address>/<database schema you want to connect to>", "<user>", "<password>");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
hope you got it now :)

Categories