Communications link failure while connecting to mysql - java

I'm trying to connect to mysql database from my android application.
I'm getting Communications link failure error.Below is the code snippet:
public class MySqlConnector {
private Connection con = null;
private String s = "";
private String username = "root";
private String password = "password01";
private String connectionString;
public String ConnectToDb() {
connectionString ="jdbc:mysql://192.168.1.104:3306/mydatabase";
//connectionString="jdbc:mysql://10.0.0.0:3306/mydatabase";
// connectionString="jdbc:mysql://127.0.0.1:3306/mydatabase";
//connectionString = "jdbc:mysql://MainSrv04:3306/mydatabase";
// connectionString="jdbc:mysql://localhost:3306/mydatabase";
// connectionString =
// "jdbc:mysql://localhost:3306/mydatabase?user=root&password=password01&useUnicode=true&characterEncoding=UTF-8";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
con = DriverManager.getConnection(connectionString, username,
password);
Statement st = con.createStatement();
String sql = "SELECT First_Name FROM mydatabase.custinfo where CardNumber=5325784707";
ResultSet rs = st.executeQuery(sql);
s = rs.getString("First_Name");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
Log.i("MySqlConnector", "Database connection terminated");
} catch (Exception e) { /* ignore close errors */
}
}
}
if (s == "") {
s = "No Result";
}
Log.i("MySqlConnector : s=", s);
return s;
}
}
I tried all possible combinations as showed in comments and getting following error in caused by field in logcat:
while using localhost --> Caused by: java.net.ConnectException: localhost/127.0.0.1:3306 - Connection refused
while using 127.0.0.1 --> Caused by: java.net.ConnectException: /127.0.0.1:3306 - Connection refused
while using 10.0.0.0 --> Caused by: java.net.SocketException: The operation timed out
while using 192.168.1.104 --> Caused by: java.net.SocketException: The operation timed out
while using MainSrv04 --> Caused by: java.net.UnknownHostException: MainSrv04
I also pinged mysql port through telnet and it's working.
Also, I have taken care of privileges.
But still I'm getting Communications link failure error.
Any help appreciated.

Is android application is on same ntework? If not
jdbc:mysql://192.168.1.104:3306
and
jdbc:mysql://10.0.0.0:3306
will not work.
Give the proper network address of mysql.

I use latest version of adt and mysql-connector-java-5.1.17-bin.jar, this works for me :
Add the below code into your file after the line setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
and use import android.os.StrictMode;
If you use new api, add #SuppressLint("NewApi");

Related

Java program to connect azure database in Netbeans I'm getting error

I'm getting the following error:
I tried various ways I'm getting an error please see the following error.
run: java.lang.ClassNotFoundException:
com.microsoft.sqlserver.jdbc.SQLServerDriver at
java.net.URLClassLoader.findClass(URLClassLoader.java:381) at
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) at
java.lang.ClassLoader.loadClass(ClassLoader.java:357) at
java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Class.java:264) at
com.sqldbsamples.App.main(App.java:23)
BUILD SUCCESSFUL (total time: 0 seconds)
This is my code: please help me with how to connect my database to azure using java program !!!
public class App {
public static void main(String[] args) {
// Connect to database
String hostName = "testchinnaa.database.windows.net:1433"; // update me
String dbName = "Test_Gopi"; // update me
String user = "chinna"; // update me
String password = "******"; // update me
String url = String.format("jdbc:sqlserver://testchinnaa.database.windows.net:1433;database=Test_Gopi;user=chinna#testchinna;password=*****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"
+ "hostNameInCertificate=*.database.windows.net;loginTimeout=30;", hostName, dbName, user, password);
Connection connection = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url);
String schema = connection.getSchema();
System.out.println("Successful connection - Schema: " + schema);
System.out.println("Query data example:");
System.out.println("=========================================");
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName "
+ "FROM [SalesLT].[ProductCategory] pc "
+ "JOIN [SalesLT].[Product] p ON pc.productcategoryid = p.productcategoryid";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectSql)) {
// Print results from select statement
System.out.println("Top 20 categories:");
while (resultSet.next())
{
System.out.println(resultSet.getString(1) + " "
+ resultSet.getString(2));
}
connection.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Sorry, you have to figure out if you are using MySql or MSSql. You said that you used mysql. However, in your connection string, it is a sqlserver which means it is a MSSql.
Here is the tutorial for accessing database using java:
You need to download connector for your database:
For MySql: MySQL
Connector/J
For MSSql: Microsoft JDBC Driver for SQL
Server
Manually add connector jar file to your classpath. Or you can use Maven dependencies manager to install and configure the Connector/J library in your project.
<!-- Example for mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
Code sample
For MSSql:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
connection = DriverManager.getConnection("conntection_string");
String SQL = "SELECT name FROM sysdatabases;";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SQL)) {
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
For MySql:
Connection conn = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connectionUrl = "jdbc:mysql://{server_name}.mysql.database.azure.com:3306?useSSL=true&requireSSL=false&serverTimezone=UTC";;
conn = DriverManager.getConnection(connectionUrl, "username_from_portal, like: jack#mysqldemo258", "password");
rs = conn.prepareStatement("show databases").executeQuery();
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try{
if(rs != null) rs.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

Error : com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

ERROR MESSAGE in SERVER
[2019-01-07 09:44:02] ERROR
:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications
link failure
[2019-01-07 09:44:02]
[2019-01-07 09:44:02] The last packet sent successfully to the server was 0
milliseconds ago. The driver has not received any packets from the server.
But testing in local.. No problem.. No Error message..
Commit libraries..
mysql-connector-java-5.1.47-bin.jar
mysql-connector-java-5.1.47.jar
JDBC URL ALTER
jdbc:mysql://IP:3306/ID -> jdbc:mysql://IP:3306/ID?autoReconnect=true
Changed Error Message..
[2019-01-07 11:04:32] Error :
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could
not create connection to database server. Attempted reconnect 3 times.
Giving up.
ControlDAO.java
private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String URL =
"jdbc:mysql://IP:3306/ID?autoReconnect=true;
public static void CsNumberCheck(String s) {
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, "ID", "PW");
System.out.println(conn);
stat = conn.createStatement();
int result = 0;
sql = Query;
rs = stat.executeQuery(sql);
while ( rs.next() ) {
result = rs.getInt(1);
}
rs.close();
stat.close();
System.out.println(result);
CsNumberResult(result, OrangeEmail);
}
catch (ClassNotFoundException e) {
System.out.println("Driver Loading Failed..");
}
catch (SQLException e) {
System.out.println("Error : " + e);
}
}
Socket.java
ControlDAO.CsNumberCheck(s);
But nothing result about "Sysout", Only Error Message....
Check your windows services to see if your MySQL server is running. That might be a probable cause. If it's not, start it and try to reconnect.

Why can't connect MySQL with Java in local network using XAMPP

I want to connect MySQL with Java in a local network (between 3 computers) using XAMPP. But I can't do that with Java and tried to connect the database with PHP application, then connected. I think this is not XAMPP error. It may be in Java app.
My code:
Connection getcon() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String URL = "jdbc:mysql://192.168.8.101/checker";
String username = "root";
String password = "";
//Connection
con = DriverManager.getConnection(URL, username, password);
return con;
}
Exception:
run: com.mysql.jdbc.CommunicationsException: Communications link
failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException MESSAGE: java.net.ConnectException:
Connection timed out: connect
STACKTRACE:
java.net.SocketException: java.net.ConnectException: Connection timed
out: connect at
com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:276) at
com.mysql.jdbc.Connection.createNewIO(Connection.java:2666) at
com.mysql.jdbc.Connection.(Connection.java:1531) at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:661) at
java.sql.DriverManager.getConnection(DriverManager.java:247) at
connectionchecker.JDBC.getcon(JDBC.java:45) at
connectionchecker.JDBC.getdata(JDBC.java:68) at
connectionchecker.Check.incremntno(Check.java:28) at
connectionchecker.Check.jButton1ActionPerformed(Check.java:84) at
connectionchecker.Check.access$000(Check.java:15) at
connectionchecker.Check$1.actionPerformed(Check.java:50) at
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6522) at
javax.swing.JComponent.processMouseEvent(JComponent.java:3322) at
java.awt.Component.processEvent(Component.java:6287) at
java.awt.Container.processEvent(Container.java:2229) at
java.awt.Component.dispatchEventImpl(Component.java:4878) at
java.awt.Container.dispatchEventImpl(Container.java:2287) at
java.awt.Component.dispatchEvent(Component.java:4700) at
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4872)
at
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4528)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4457)
at java.awt.Container.dispatchEventImpl(Container.java:2273) at
java.awt.Window.dispatchEventImpl(Window.java:2724) at
java.awt.Component.dispatchEvent(Component.java:4700) at
java.awt.EventQueue.dispatchEventImpl(EventQueue.java:743) at
java.awt.EventQueue.access$400(EventQueue.java:97) at
java.awt.EventQueue$3.run(EventQueue.java:694) at
java.awt.EventQueue$3.run(EventQueue.java:691) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:716) at
java.awt.EventQueue$4.run(EventQueue.java:714) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:713) at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:220)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:135)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:123)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:119)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:111)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
** END NESTED EXCEPTION **
last packet sent to the server was 43 ms ago. my msg is conn ok
java.lang.NullPointerException
JDBC class:
public class JDBC {
private static JDBC j;
Connection con = null;
private JDBC() {
}
public static JDBC getJDBC() {
if(j == null){
j= new JDBC();
}
return j;
}
Connection getcon() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
//String URL = "jdbc:mysql://127.0.0.1/checker";
String URL = "jdbc:mysql://192.168.8.101:80/checker";
String username = "root";
String password = "";
//Connection
con = DriverManager.getConnection(URL, username, password);
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e);
}
return con;
}
void setdata(String sql) {
try {
if (con == null) {
getcon();
}
con.createStatement().executeUpdate(sql);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
ResultSet getdata(String sql) throws Exception {
if (con == null) {
getcon();
System.out.println("my msg is conn ok");
}else{
System.out.println("my msg is conn not ok");
}
ResultSet rset = con.createStatement().executeQuery(sql);
return rset;
}
}
You need to pass the port number of the XAMPP after the ip address.
The default port number is 80 for XAMPP.
String URL = "jdbc:mysql://192.168.8.101:80/checker";
Or try this one below
String URL = "jdbc:mysql://192.168.8.101:8080/checker";
Problem lies here
String URL = "jdbc:mysql://192.168.8.101:80/checker";
Note, this should represent your db server and port where your db is running. Above url is wrong as, port 80 is default port number for Apache server. But, you need to use mysql port, which is 3306 (default).
Instead, you should try
String URL = "jdbc:mysql://192.168.8.101:3306/checker";
I'm assuming checker is database name.

java.sql.Connection not working when import from a different class

I have managed to pinpoint two of the mistakes I had and will therefore update my question.
Firstly, my previous error:
java.lang.ClassCastException: Bootstrap method returned null
was fixed by simply adding this line to build.graddle (app) dependencies:
implementation group: 'com.google.protobuf', name: 'protobuf-java', version: '3.6.0'
So that was nice, However this did not solve all my issues. This is my current register button method:
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
conn = Utils.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
});
As you can see I am focusing solely on getting a connection as it seems to be the heart of the problem. In debugging I also modified getConnection() to the following:
public static Connection getConnection() {
String driver = "com.mysql.cj.jdbc.Driver"; //com.mysql.jdbc.Driver doesn't work either
String url = "url";
String username = "user";
String password = "pass";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return null;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(url,username, password);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return null;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return connection;
}
And this is the error that I am receiving now:
I/System.out: Connection Failed! Check output console
W/System.err: java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
W/System.err: Caused by: com.mysql.cj.exceptions.CJCommunicationsException: 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.
Caused by: java.net.SocketException: socket failed: EACCES (Permission denied)
I will keep this up to date on further changes. Again, if the issue is obvious I apologize in advance. Thanks for the help!

Android studio can't connect to database in Azure sql server

I am using android studio to develop an application and using Azure Sql Server to host my database. The problem is I was able to connect to my database on SQL server but it has an error of Object not found in my database.
I found out that it might be connecting to my master database instead of the database I want it to connect to. Is there any solution to solve the problem?
package com.example.lenovo.testing1;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.*;
public class ConnectionClass {
String hostName = "haozailai.database.windows.net";
String dbName = "haozailai";
String user = "username";
String password = "password";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String ConnURL;
Connection conn = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://haozailai.database.windows.net:1433;database=haozailai;user=username;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
}catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return conn;
}
}
Picture of my database structure
I tried to connect my sqlserver via java jdbc and did not reproduce your issue.
I can connect to my application db successfully.
My test code:
import java.sql.*;
public class Test {
public static final String url = "jdbc:sqlserver://***.database.windows.net:1433;database=***;user=***password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
public static final String name = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static Connection conn = null;
public static PreparedStatement pst = null;
public static Statement stmt = null;
public static ResultSet rs = null;
public static void main(String[] args) {
try {
String SQL = "select * from dbo.Student";
Class.forName(name);
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close() {
try {
conn.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
After some research, I found out it is because of your connect url.
You need to modify your connect url :
jdbc:jtds:sqlserver://haozailai.database.windows.net:1433/<your application db name> ...
You could refer to the pages below for more details.
https://sourceforge.net/p/jtds/discussion/104389/thread/a672d758/
how to connect sql server using JTDS driver in Android
Update answer:
I have made a slight adjustment to your connect URL and can connect to my application database normally.
try {
String SQL = "select * from dbo.Student";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://***.database.windows.net:1433/<your database name>;user=***;password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
Notice that remove the database=*** and add "/<your database name>" after your host string.
Please refer to the above code and try again.Any concern, please let me know.
Hope it helps you.
I know this answer is waay too late, but I found this video that totally works: https://www.youtube.com/watch?v=WJBs0zKGqH0
The thing is, you have to download a jtds jar, the guy in the video says where you can get it from and also, you need to add "jtds" before "sqlserver" in connection url and edit the way the 'databe' is written in the connection url, like this:
jdbc:jtds:sqlserver://serverName.database.windows.net:portNr:DatabaseName=dbName;user=....

Categories