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)
Related
I am trying to connect with My company's database which is 'MariaDB', using Java, I am using following code:
package co.companyname.helpers;
import java.sql.*;
public class DatabaseConnectivity {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
String query = "select * from time_clock limit 10";
try {
Class.forName("org.mariadb.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(
"jdbc:mariadb://host_url:3306", "root", "password");
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = query;
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
At above I have used host_url, but I am using actual host within string, now I am getting following error:
java.lang.ClassNotFoundException: org.mariadb.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:315)
at co.company_name.helpers.DatabaseConnectivity.main(DatabaseConnectivity.java:10)
Goodbye!
I need to know, if I am doing anything wrong.
Thanks.
I'm trying to connect my android studio to my AWS rds with JDBC.
public void GetText(){
TextView tx1 = findViewById(R.id.login_title);
ConnectionURL = "jdbc:mysql://awsrds-endpoint:3306/supplychain?user=admin&password=admin123";
try {
System.out.println("Loading driver...");
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find the driver in the classpath!", e);
}
Connection conn = null;
Statement setupStatement = null;
Statement readStatement = null;
ResultSet resultSet = null;
String results = "";
int numresults = 0;
String statement = null;
try {
System.out.println("Connecting ...");
conn = DriverManager.getConnection(ConnectionURL);
System.out.println("Connected");
readStatement = conn.createStatement();
resultSet = readStatement.executeQuery("SELECT S_ID FROM STAFF;");
conn.close();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
and my error:
I/System.out: SQLException: Could not create connection to database server.
SQLState: 08001
VendorError: 0
The question here doesn't matter- do NOT connect to a db like this. In order to do this, you are putting your username and password in cleartext in your app. It is trivial to decompile the app and get it. This is unsafe. You should only ever access remote dbs via a webservice. That way your username and password do not need to leave your own devices.
When I am connected to the client network (using VPN) then i am successfully able to fetch the data from the database. But if I disconnect from the client network and run locally the same function then I am getting below error -
Connection Failed:SAP DBTech JDBC: Cannot connect to jdbc:sap://saphsg.XXXX.XX.com:30015 [Unknown host saphsg.XXXX.XXX.com:30015 [null], -709].
Below is the code which i am using -
public static void dbConnection(String query) throws ClassNotFoundException {
Connection connection = null;
try {
Class.forName("com.sap.db.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:sap://saphsg.XXXX.XXX.com:30015?encrypt=true&validateCertificate=false", UserID, Password);
} catch (SQLException e) {
System.err.println("Connection Failed:" +e.getMessage());
}
if (connection != null) {
try {
System.out.println("Connection to HANA successful!");
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery(query);
while (resultSet.next()){
String Name1 = resultSet.getString(1);
String Name2 = resultSet.getString(4);
String Name3 = resultSet.getString(5);
System. out.println(Name1+"----"+Name2+"----"+Name3);
}
} catch (SQLException e) {
System.err.println("Query failed!");
}
}
}
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.
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();
}