Android Studio + MySQL Workbench: can't connect to database using JDBC - java

I'm fairly new at developing apps. I've began a tutorial on how to connect an app to a database using JDBC driver. I'm using Android Studio and MySQL Workbench.
Here is a sample of the code:
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtest", "root", "123");
stmt = conn.createStatement();
String query = "SELECT * from tblHockeyPlayers";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
double number = rs.getDouble("number");
hockeyPlayersMap.put(name, number);
}
msg = "Process successful.";
rs.close();
stmt.close();
conn.close();
} catch (SQLException connError) {
msg = "An exception was thrown for JDBC";
connError.printStackTrace();
} catch (ClassNotFoundException e) {
msg = "A class not found exception was thrown";
e.printStackTrace();
} finally {
try {
if (stmt != null){
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
The line conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD); always triggers this error (catches an SQLException):
java.sql.SQLException: Unable to connect to any hosts due to exception: java.net.SocketException: java.net.ConnectException: failed to connect to /127.0.0.1 (port 3306) from /:: (port 35618): connect failed: ECONNREFUSED (Connection refused)
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.net.ConnectException: failed to connect to /127.0.0.1 (port 3306) from /:: (port 35618): connect failed: ECONNREFUSED (Connection refused)
STACKTRACE:
java.net.SocketException: java.net.ConnectException: failed to connect to /127.0.0.1 (port 3306) from /:: (port 35618): connect failed: ECONNREFUSED (Connection refused)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:143)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:225)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1805)
at com.mysql.jdbc.Connection.<init>(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
at com.sportsknowledge.mysqlexampleproject.MainActivity$GetData.doInBackground(MainActivity.java:69)
at com.sportsknowledge.mysqlexampleproject.MainActivity$GetData.doInBackground(MainActivity.java:50)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
** END NESTED EXCEPTION **
I have tried to use XAMMP and EasyPHP and read all sort of things that didn't work out. I don't know what else to try.

Related

How to deal with 'CommunicationsException: Communications link failure' in MAMP? [duplicate]

This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 4 years ago.
I have settled MAMP on my machine and last time when I used that code on my old computer and with another database that works pretty well. Now I cannot understand where I am wrong.
public class JDBC {
private static String DBURL = "jdbc:mysql://localhost:3306/BookReservationDatabase";
private static String DBLOGIN = "root";
private static String DBPASSWORD = "root";
public static void main(String[] args) {
// Step1: register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// Step 2: Establish the connection to the database
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = DriverManager.getConnection(DBURL, DBLOGIN, DBPASSWORD);
// Step 3: Create statements (SQL queries)
stmt = conn.createStatement();
// Step 4: Execute statements and retrieve results
rset = stmt.executeQuery("SELECT * FROM Users");
// Step 5: Analyze results
while (rset.next()) {
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Step 6: Release resources
try {
if (rset != null)
rset.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (stmt != null)
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
My database name is BookReservationDatabase, I use root as a login and password on PhpMyAdmin.
I have got the following errors :
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.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:342)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2188)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2221)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2016)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:776)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at features.JDBC.main(JDBC.java:26)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:301)
... 15 more
The error must be among DBURL,DBLOGIN and DBPASSWORD. Because the code generate error at the connection
conn = DriverManager.getConnection(DBURL, DBLOGIN, DBPASSWORD);
java.net.ConnectException: Connection refused (Connection refused)
clearly signals a communication error on the machine on which you run this code. This could be caused by many reasons, thus I merely list the most likely ones:
MySQL is not running at all.
Did you start it? Verify by inspecting running process lists (depends on OS).
MySQL is not listening on Port 3306 which is the default port.
Did you change it? If so, change your code/config accordingly.
In case a firewall is active, check the rules that could prevent connections on port 3306.
Hope it helps.

connect to impala error Connection refused?

I am trying to connect from Java program to impala using the below driver
com.cloudera.impala.jdbc4.Driver
but i am getting a sql exception, bellow stack-trace
java.sql.SQLException: [Simba][ImpalaJDBCDriver](500310) Invalid operation: java.net.ConnectException: Connection refused: connect;
at com.cloudera.impala.hivecommon.api.HiveServer2ClientFactory.createTransport(HiveServer2ClientFactory.java:224)
at com.cloudera.impala.hivecommon.api.HiveServer2ClientFactory.createClient(HiveServer2ClientFactory.java:52)
at com.cloudera.impala.hivecommon.core.HiveJDBCConnection.connect(HiveJDBCConnection.java:597)
at com.cloudera.impala.jdbc.common.BaseConnectionFactory.doConnect(BaseConnectionFactory.java:219)
at com.cloudera.impala.jdbc.common.AbstractDriver.connect(AbstractDriver.java:216)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.gcs.virdict.InsertImpala.generateValue(InsertImpala.java:86)
Caused by: com.cloudera.impala.support.exceptions.GeneralException: [Simba][ImpalaJDBCDriver](500310) Invalid operation: java.net.ConnectException: Connection refused: connect;
I am also attaching the code below for reference
private void connectionImpala() {
try {
Class.forName(IMPALA_DRIVER_NAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
Connection con = null;
Statement stmt = null;
try {
con = DriverManager.getConnection( "jdbc:impala://IP:21050/default;user=abcde;password=abcde");
stmt = con.createStatement();
// ResultSet rs = stmt.executeQuery(sqlStatement)
} catch (SQLException e) {
e.printStackTrace();
}

Connection Issues with Java program using oracle 11g

I am having connection issues with my java program interacting with oracle 11g using ojdbc7.jar. I am using jdk 1.8 on windows 7 platform. I'm getting an error with the connection.
I'm writing my whole program below:
package mydao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AdminDAO {
Connection con;
public void connectionMethod() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:oracleEE", "system", "tiger");
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void loginCheck(String uid, String pwd) {
connectionMethod();
try {
String sql = "SELECT * FROM ADMIN_LOGIN WHERE ADMINUID=? AND ADMINPWD=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, uid);
ps.setString(2, pwd);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
rs.getString(1);
rs.getString(2);
rs.getString(3);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
AdminDAO a = new AdminDAO();
a.loginCheck("avi", "avi3");
}
}
But I'm getting error like this:
run:
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:673)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:715)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:385)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:30)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:564)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at mydao.AdminDAO.connectionMethod(AdminDAO.java:33)
at mydao.AdminDAO.loginCheck(AdminDAO.java:43)
at mydao.AdminDAO.main(AdminDAO.java:74)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:445)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:464)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:594)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:229)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1360)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:486)
... 9 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:162)
at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:411)
... 14 more
Exception in thread "main" java.lang.NullPointerException
at mydao.AdminDAO.loginCheck(AdminDAO.java:61)
at mydao.AdminDAO.main(AdminDAO.java:74)
Java Result: 1
Can anyone help me getting out of this problem? I'm confused how to recover from this error.
Please try to start the TNS-Listener service in services.msc.
It seems that the server is not listening on the specified port or hostname.
Check if your service is running and if so check the port on which it is listening. If your oracle service is listening in different port update the same in your code and check.

Refused Connection from android to sqlserver

This is my code to connect to SqlServer from Android Application
private Connection CONN(String _DB, String _server)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String connectionUrl = "jdbc:sqlserver://AhmedPc:1433; Instance=SQL2008;" +
"databaseName=admin1;integratedSecurity=true;";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next())
{
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
return con;
}
I get this Error
When I use the Ip address 42.xx.xx.xx i get this::::
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net.ConnectException: failed to connect to / (port 1433): connect failed: ETIMEDOUT (Connection timed out)
When i use the 127.0.0.1 i get this:::::
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host has failed. java.net.ConnectException: failed to connect to / (port 1433): connect failed: ECONNREFUSED (Connection refused)

Communications link failure while connecting to mysql

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");

Categories