Android: connect to mysql doesn't work - java

I have the same code written in Java and in Android to connect to a mysql-server.
The same code in Java works, but in android it doesn't.
My Code:
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
String url1 = "jdbc:mysql://192.168.178.91:3306/db_meinungskanal?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
String user = "user1";
String password = "root";
connection = DriverManager.getConnection(url1, user, password);
if (connection != null) {
System.out.println("Connected to the database");
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
In my android app I have granted acces to the internet with permissions, so I'm able to connect to internet.
If I run the code in android it doesn't work and I get the following:
System.out: An error occurred. Maybe user/password is invalid 02-11
20:29:13.261 17036-17036/camelgmbh.com.meinungskanal W/System.err:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure 02-11 20:29:13.261
17036-17036/camelgmbh.com.meinungskanal W/System.err: The last packet
sent successfully to the server was 0 milliseconds ago. The driver has
not received any packets from the server.
Need help ;D

Android is not supporting MYSQL.You can utilize SQLite or Create web services to access MySQL data from the app.

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.

Java JDBC and Oracle Wallet Connection

How to use oracle wallet
Using this as reference. I am still unable to connect to Oracle Wallet. Sample code below.
Errors
--
java.sql.SQLException: encountered a problem with the Secret Store. Check the wallet location for the presence of an open wallet (cwallet.sso) and ensure that this wallet contains the correct credentials using the mkstore utility: java.io.IOException: oracle.security.crypto.cert.PKCS12.getAuthSafesAsList()Ljava/util/ArrayList;
at oracle.jdbc.driver.PhysicalConnection.getSecretStoreCredentials(PhysicalConnection.java:1314)
at oracle.jdbc.driver.PhysicalConnection.parseUrl(PhysicalConnection.java:1198)
at oracle.jdbc.driver.PhysicalConnection.readConnectionProperties(PhysicalConnection.java:982)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:646)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:428)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:38)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:691)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
--
Sample Code
public static void main (String [] args) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
determineAndSetTnsHome();
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:/#xxx");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
private static void determineAndSetTnsHome() {
String tnsAdmin = System.getenv("TNS_ADMIN");
if (tnsAdmin == null) {
String oracleHome = System.getenv("ORACLE_HOME");
if (oracleHome == null) {
return; //failed to find any useful env variables
}
tnsAdmin = oracleHome + File.separatorChar + "network" + File.separatorChar + "admin";
}
System.setProperty("oracle.net.tns_admin", tnsAdmin);
}
--
Notes
Confirmed that wallet is setup.
- Doing sqlplus $xxx connects fine.
- Doing mkstore -wrl -listCredential returns the entry after entering wallet password.
Thanks in advance.
Can you check out the blog for more details?
Check if you are using TLSv1.2 and Oracle Wallets require additional jars (oraclepki.jar, osdt_core.jar, and osdt_cert.jar)
Your wallet may be installed and configured correctly, but that does not mean the wallet is currently open. Anytime the database is restarted, the wallet needs to be opened.
Run a sample query against a known table in your schema in SQL*Plus (connecting is not enough)
If the wallet is not open you will get the following error:
ORA-28365: wallet is not open
This query should give you the status of the wallet:
select wrl_type wallet,status,wrl_parameter wallet_location from v$encryption_wallet;
In order to open a wallet, run the following command, replacing "myPassword" with the password you chose:
ALTER SYSTEM SET ENCRYPTION WALLET OPEN IDENTIFIED BY "myPassword";

Java JDBC Communications link failure after deploying online

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

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