I'm trying to connect my Android app to my local machine database MS SQL. This is my connection string:
jdbc:jtds:sqlserver://localhost:1433/DajSve;encrypt=false;user=root;password=null;instance=FALE//SQLEXPRESS;
And I got this error:
java.sql.SQLException: Network error IOException: failed to connect to localhost/127.0.0.1 (port 1433): connect failed: ECCONREFUSED (Connection refused)
I tried a lot of things. Changed a connection string a lot of times, enabled TCP/IP and set it to port 1433, also turned off firewall but nothing helped. I'm always getting the same SQL Exception. I'm using SQL Server 2016..
try {
Class.forName(className).newInstance();
connection = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/DajSve;encrypt=false;user=root;password=null;instance=FALE//SQLEXPRESS;");
System.out.print("Uspjesno spojeni na bazu");
Statement stmt = connection.createStatement();
ResultSet reset = stmt.executeQuery("select * from Korisnik");
if (!reset.isBeforeFirst() ) {
System.out.println("nema podataka");
}else{
System.out.println("ima podataka");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.print("Greska pri spajanju na bazu");
} catch (ClassNotFoundException e){
System.out.print("Greska - klasa nije pronađena");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
I know there is a lot of similar questions but none of the answers have helped
failed to connect to localhost/127.0.0.1
Your Android device isn't running a SQL Server. Give the actual server address on your network (but actually don't because you shouldn't be storing database credentials as part of your app, plus persistent JDBC connections kill battery life).
It's not a local database when your code exists on a remote device
You will actually want to create a new application that is acts as a backend API between your Android app and the database, where you can expose functions that connect to your database and parse the results there rather than doing it all in the Android app
Related
Hello every body I'm working on application which is sends data from android app to MS-SQL server and main windows software in C#, which is receives data from MS-SQl server.
The problem is the programs takes too time to build a connection especially in android app some times it crash the app.
By the way the Internet speed some times goes week in our country.
I searched for a solution but not found in internet and I cannot figure out any way to solve it.
And I see the Viber, Watsapp, Massenger ... etc it sends data instantly or synchronously even if Internet speed is week.
So can I get some help and suggestion.
And there is a connection Helper method :
public Connection connections(){
IP="www.examlple.net";
DB="DB_test";
DBUserName="admin";
DBPassword="*****";
StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection=null;
String connectionURL=null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
connectionURL ="jdbc:jtds:sqlserver://"+IP+";DatabaseName="+DB+";integratedSecurity=true;user="+DBUserName+";password="+DBPassword;
connection = DriverManager.getConnection(connectionURL);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return connection;
}
For the sake of completeness, with JTDS you can set both a loginTimeout and a socketTimeout on a connection string. Refer to the remarks on these here.
But as others have said, you should go through a web API of some sort. Do you really want to expose your SQL server to the internet?
Also, I just noticed you have specified integrated security=true, and you have also specified a username and password. You can't do that. One is for windows auth (integrated security) and the other is for SQL auth (user and password). You would have to use a username and password. But don't. Don't do this. go through a web API.
I can't connect remote database. When I connect my own database on localhost, it connects. What's wrong?
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
Caused by: 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.
Caused by: java.net.ConnectException: Connection refused: connect
Java Code:
String url = "jdbc:mysql://ipadress:3306/database?autoReconnect=true&useSSL=false";
String username = "username";
String password = "password";
String query = "SELECT * FROM database";
System.out.println("Connecting database...");
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
//Uruchamiamy zapytanie do bazy danych
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
}
connection.close();
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
I can login to database on PHPMyAdmin, I have no root account, it's my friend's database. I checked if port 3306 is open here: http://www.yougetsignal.com/tools/open-ports/ and it's closed. Where can I open it? In router settings in "port forwarding"? What private IP and type(TCP or UDP) should I set to open this port?
(Apologies if this answer is incomplete, but there is too much that does not fit in comments)
1) Don't ignore exceptions. This is bad : with // handle the error and nothing else in your catch block, in case of error there, your code will not report the error, and will move on with the execution (it should exit/break/return, depending on where that piece of code is).
2) I think checking "SHOW GLOBAL VARIABLES LIKE 'PORT';" is not enough. Ask your friend if the database daemon actually listens to port 3306 on a network interface that you can reach. MySQL can be configured with networking disabled (skip-networking), or enabled but only for local machine (bind-address=127.0.0.1 or localhost -- it should be bind-address=0.0.0.0 or bind-address=hostname or public IP address...).
To check for that yourself, if you are on linux, try with nc or telnet (install nc if you don't have it): nc remotehost 3306. If you get "connection refused", the error is definitely not in your java code, but in the server setup.
I am trying to connect to Azure SQL Data Warehouse through JDBC. I am getting the following exception.
*
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host tcsqldatawh.database.windows.net, port 1433 has failed. Error: "null. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:242)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2280)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:493)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1387)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1068)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:904)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:451)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1014)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at testsqldw.SQLDatabaseConnection.main(SQLDatabaseConnection.java:30)
*
I have seen similar questions asked about connecting to the SQLServer DB here.
I configured the database to allow access to my IP using the process here.
Please check the code below:
package testsqldw;
import java.sql.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://databaseserver.database.windows.net:1433;"
+"database=databaseserver;"
+"user=username#databaseserver;"
+ "password=password;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
System.out.println("Total connection string is---\n"+connectionString);
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String createSql = "create table employee(employee_id varchar(20));";
statement = connection.createStatement();
boolean status=statement.execute(createSql);
System.out.println(status);
// Print results from select statement
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the connections after the data has been handled.
if (statement != null) try { statement.close(); } catch(Exception e) {}
if (connection != null) try { connection.close(); } catch(Exception e) {}
}
}
}
Total connection string is
jdbc:sqlserver://databaseserver.database.windows.net:1433;database=databaseserver;user=username#databaseserver;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
Please help me in resolving the issue.
Per my experience, the issue may be caused by the following reasons:
The SQL Server which you have created may not work fine.
You may use incorrect JDBC connection string.
For the first reason, you could use some client tools to connect to the SQL server. If you could connect to the server, that indicates the SQL server is ok.
If not ,you could create a new SQL Server. After then, you could create a new SQL Data Warehouse according to this URL https://azure.microsoft.com/en-us/documentation/articles/sql-data-warehouse-get-started-provision/.
The URL also includes the firewall config method.
I use the SQL Server InTouch to connect to the SQL Server. The followings are some description images.
You could get the parameters by the Azure Portal. The port number is 1433.
The following picture indicates that your server is ok.
For the second reason, you could copy the connection string from the azure portal and modify the password only.
Hope it helps. Any concerns, please feel free to let me know.
I have the following piece of code,
String url = "jdbc:oracle:thin:#127.0.0.1:1521:oracle";
Connection con=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
con=DriverManager.getConnection(url, "user", "password");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I don't understand the url part of it. When i run this i get java.sql.SQLException: Io exception: The Network Adapter could not establish the connection
On searching for this error in google,
Based on suggestions, i checked telnet 127.0.0.1 1521 in cmd prompt which didn't succeed.
Now what might be the problem? What should i do if telnet is not able to connect ?
Also, Please explain what does this URL will actually do? Am new to this please help.
The message "could not establish the connection" usually means that the connection could not be made - there is something incorrect about the connection url (IP address, db name) or the credentials (username/password).
If you need to create a database locally, you can use Oracle XE. (http://www.oracle.com/technetwork/database/database-technologies/express-edition/overview/index.html) SQL Developer is a useful Oracle GUI for accessing the database or for trying out your connection information. (http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html)
I have a problem establishing an connection to my MySql database via Java/Android. I have a database file (MyDatabase.db) on a Windows7 computer in my network. When I'm developing from another Windows7 computer (the file is accessible via the Windows Explorer and I can make changes to the database via SQLDatabaseExplorer) out of Eclipse the following Code works, but when installing my Application on my Galaxy Tab the "DriverManager.getConnection()" returns null.
try {
String url = "http://192.168.178.21/Users/test/userdata/Database/MyDatabase.db";
Class.forName ("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection (url);
System.out.println ("Database connection established");
} catch (SQLException e) {
Log.d("SQLException", "e.toString()");
}
The SQLException logged in LogCat is:
java.sql.SQLException: path to '//192.168.178.21/Users/test/userdata/Database/MyDatabase.db': '/192.168.178.21' does not exist
I guess my problem lies in the url String...? But I did not figure out how to change it, so that the connection can be established.
Thanks for any help,
Tim
EDIT:
Thanks for your help so far! I have written the question yesterday out of my mind, without looking onto my code... I'm sorry for that, because I have mixed up a lot of things... It is not a MySql-database but a sqlite-database... But I think that doesn't change a lot in coding. I'm using an jdbc sqlite driver. When starting the lines below in an Java-Eclipse Project everything works fine and the connection can be established. But on my Device I still got the Nullpointer...
Yesterday I have changed my code so that it should fit your advices. But the problem still resists... To be sure that it does not have to do with some rights or network settings I have copied the DB-File onto my Androiddevice and tried to connect to it directly with the following lines of code:
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = DriverManager.getConnection("jdbc:sqlite://mnt/sdcard/MyVideos34.db");
if (conn == null) {
Log.d("ConnectionError", "Connection is null");
return;
}
But also here getConnection throws a NullPointer and I don't know why... Did somebody have a assumption why the connection can be established out of Eclipse and fails on my Androiddevice? May I could have a wrong driver, that does not work from the device, but from Eclipse...?
Thanks in advance!
The url format for the MYSQL conenction string is
jdbc:mysql://[host][,failoverhost...][:port]/[database] »
[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
If the host name is not specified, it defaults to 127.0.0.1. If the port is not specified, it defaults to 3306, the default port number for MySQL servers.
jdbc:mysql://[host:port],[host:port].../[database] »
[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
Here is a sample connection URL:
jdbc:mysql://localhost:3306/sakila?profileSQL=true
please change accordingly
JDBC urls have the form : jdbc:mysql:/// but look at the duplicate code. You probably don't want to connect directly to a database from a mobile like this but will prefer a web service wrapper to do it.
try {
String url = "jdbc:mysql://localhost:3306/MyDatabase?user=root&password=root";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection (url);
System.out.println ("Database connection established");
} catch (SQLException e) {
System.out.println("SQLException" + e.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}