I have a java program which takes its information from MySQL it works fine when I use localhost to connect to it but whenever i put ipaddress in it it does not work.
My connection code and exception are as follows.
package connection;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* #author rpsal
*/
public class DBConnection {
public static Connection connect()//working on local host
{
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+getIpAddress()+"/ChatMaster";
conn = DriverManager.getConnection(url, "root", "");
} catch (Exception e) {
System.out.println("Exception in connect" + e);
}
return conn;
}
public static String getIpAddress() throws Exception {
InetAddress inetAddress = InetAddress.getLocalHost();
return inetAddress.getHostAddress();
}
}
When i use String url = "jdbc:mysql:///ChatMaster"; it works fine.
The exception i am getting is as follows.
Exception in connectjava.sql.SQLException: null, message from server: "Host 'Rp-Salh' is not allowed to connect to this MySQL server"
As the error tells you, that the ip Adress hasn't the rights to access this database, I think it is not your code which is wrong.
I don't know if it is the same for MySQL, but for postgresql I
needed to define in the database to allow remote connections.
I think inetAddress.getHostAdress() will return the host name (suh as Rp-Salh)
So I recommend you to use this method
inetAddress.getLocalHost()
As I can see from the error log. The InetAddress.getLocalHost(); is not returning the correct IP address.
Please try connection it by providing hard-coded IP address (Just for testing to get sure).
You can get system IP address in windows by typing ipconfig on CMD.
You need to make sure 2 things.
Check MySQl port 3306 is already opened or not. Here are sample remote connection String
String url = "jdbc:mysql://192.168.1.121:3306/ChatMaster";
Check database user name and password is correct.
Update mysql config file (probably in server file directory etc/mysql/my.conf) check if it is configured with 127.0.0.1(default) as a host address and change it to your IP.
As it turns out #Jan. St 's pointed me to the right direction as the problem wasn't in my code or any of getting ipaddress problem it was just that by default remote root access is disabled in mysql. I just followed the answer in the following link and it worked.
How to allow remote connection to mysql
Note: make sure you also follow 2nd answer in the same post if first answer on its own did not work.
Related
I am creating a program for a local organization to take inventory. App connects to SQL Server via MSSQL 8.2 connector. App on phone should allow for receiving and sending item information. I have a static class to connect to the database, that handles the connection. In Eclipse, I am able to successfully connect and query the database. In Android studio, I get errors on every attempt to connect.
-Server is hosted on same pc.
-Ports have been configured, repeatedly. Currently have inbound and outbound rules for TCP and UDP fully open. Dynamic ports are on for SQL server. Services for SQL server have been restarted dozens of times. 1433 has been enabled and toggled off, but are currently blank.
-Attempted to connect by IP address, host cannot be resolved
-Permissions edited to allow login access to modify the database
-Integrated security and TLS security tried at different times, both failed.
List of errors:
Connection to the host BLACK-G, "xxxxx" port 1433, has failed.
TCP/IP connection to the host failed, unable to resolve host.
Connection to the host named BLACK-G instance sqlexpress failed,No
address associated with hostname, open up UDP traffic to port 1434
Unknown host exception. Unable to resolve host BLACK-G
Connection Refused
Failed to connect
Connection to the host 192.168.1.219 has failed. Failed to connect to
192.168.1.219 (port 1433) from 192.168.1.87(port 33654) after 2478ms Verify connection properties.
Here is the code
package com.example.ccupboard_1;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseJAVA {
// #RequiresApi(api = Build.VERSION_CODES.KITKAT)//public static void main(String[] args) {
public static String Connect() {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://BLACK-G\\SQLEXPRESS;user=ay7;password=343434;databaseName=ayTestDatabase2;" ;
ResultSet resultSet = null;
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT Fname, Lname from dbo.Customers";
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
result += (resultSet.getString("Fname") + " " + resultSet.getString("Lname")+"\n");
}
} catch (SQLException e) {
e.printStackTrace();
result = e + "";
}
return result;
}
}
Snippet from main activity that calls connect method:
case R.id.buttonSignOut: { //used to test connection currently, simply attempts to connect and //returns the value to a textview on the page
Thread thread = new Thread() {
public void run() {
textviewLowItemAlert.setText(DatabaseJAVA.Connect());
}
};
thread.start();
break;
What would be the next step in resolving this issue? It works in Eclipse, but not in studio. I've tried more than a dozen different connection Strings, and most of them threw the same errors. Does my server not allow access to Android Studio? Most of the errors seem to be Android studio being incapable of locating it on the server.
Here's a snippet from a working app of mine where I can connect succesfully to a local ms sql.
In a config file I set the connection info.
public static String dbUser = "user";
public static String dbPassword = "password";
public final static String sqlString = "jdbc:jtds:sqlserver://ip:port//INSTANCENAME";
Then I start the connection like this.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
DriverManager.setLoginTimeout(5);
connection = DriverManager.getConnection(Config.sqlString, Config.dbUser, Config.dbPassword); // Connect to database
if (connection == null) {
ConnectionResult = "Verify Internet Connection";
Toast.makeText(activity, ConnectionResult, Toast.LENGTH_LONG).show();
Finally just do the query and close the connection.
Alright, was finally able to figure it out, with the JDBC-JTDS connector mentioned by JoaquinAlvarez.
Here's what happened:
-Used the connection info he provided, with my IP address, and a higher timeout
-Network Error IOException, EHOSTUNREACH(No route to host),
-Router changed my IP address, so had to fix that
-After that, I used my PCNAME\SQLEXPRESS for the the for the instance
-It returned Instance Unreachable, so I changed to SQLEXPRESS alone
-Then it returned DB Closed connection
-I looked at Windows Event Viewer, and it said:
"Encryption is required to connect to this server but the client library does not support encryption; the connection has been closed. Please upgrade your client library."
-I checked the SQL server in SQL SERVER Configuration Manager... Force Encryption was turned on.
-Tried again, and the JTDS connector finally connected to the Database and I was able to do things. No help with the MSSQL one yet though.
Thank you Mr. Alvarez!
This question already has answers here:
IO Error: The Network Adapter could not establish the connection
(12 answers)
Closed 3 years ago.
I'm trying to connect to a database which is hosted in a remote machine. I have a java project in my local and it has to connect to DB which is in remote machine for an update. What is the java code which I can use to connect. Traditional code of connection doesn't work and it shows below error.
import java.beans.Statement;
import java.sql.*;
public class connectTest {
public static void main(String[] args) {
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:#172.25.250.183:1521/aaadv4","boomerang","Telus2014");
Wrapper stmt=con.createStatement();
ResultSet rs=((java.sql.Statement) stmt).executeQuery("select * from ttv_dhcp_log.ACCT_MSG where SUB_IF='BACUPQXQOT01 PON 1/1/12/02:21.1.1'");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
I expect it to connect to DB but it fails with below message.
java.sql.SQLException: Io exception: The Network Adapter could not
establish the connection
There could be a couple of things you need to verify.
Check if the port is accessible from the machine . Use comamnds like telnet to check that.
Ex: telnet IPaddress portnumber
Check your firewall in your machine to see if connections to the port range are allowed or not.
Check the firewall rules in the machine where Oracle db is hoster as well.
Ensure your Credentials are correct.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = null;
connection = DriverManager.getConnection("jdbc:oracle:thin:#172.25.250.183:1521:aaadv4","username","password");
connection.close();
Use the above. Your DB connection URL contains a "/" instead of ":" . Also, ensure your IP address is accessible from your machine. If you are in the same network. It should be. If not, follow the debugging steps given above.
I got a google cloud platform - compute engine instance, which I installed MySQL server on.
And now I can't get any signal of life our of the VM the sql installed on,
for exsample:
package com.company;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void connection(){
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("in conncection");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void connectToMySQL(){
connection();
String host = "jdbc:mysql://hotsIP:3306/DBname";
String user = "user";
String pass = "password";
try {
Connection connection = DriverManager.getConnection(host,user,pass);
System.out.println("???");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
connectToMySQL();
}
}
It's take a few second like he trying to connect and the EXEPTION
in conncection
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
What I done to make it work:
in the my.conf:bind address = 0.0.0.0, skip-external-locking comment out
restart the server
looked if the server is active
looked if the server listening to the port
looked if its TCP
I don't know what to do anymore.
You have to make the following change to your my.cnf file
my.cnf
bind-address = www.000webhost.com (OR)
bind-address = xx.xx.xx.xx (IP Address)
You need to restart your MySQL service, once this setting is changed.
Also worth noting is the point that MAMP/ MAMP Pro sets MAMP_skip-networking_MAMP by default. You've to disable this line in your my.cnf
And if you don't have any user login issues, you should be able to connect to the MySQL Database from your Java code.
In my case the root cause was: Firewall. I was trying to run the application at work.
What was interesting is that the App Engine Standard running locally actually generated a non-error log in Google Cloud Platform Logs, making me discard the firewall hypotheses.
Solution: I found out bringing my notebook from home and connecting to company's network, did not work. When I connected to the shared connection in my mobile, worked perfectly.
I have downloaded JDK 6 and also I have sqljdb4.jar and I have database.properties file that content the following data
database.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
database.url=jdbc:sqlserver://.;databaseName=UserInfo;integratedSecurity=true;
database.username=sa
database.password=admin
B.N : I'm installing the server on my machine and the server name = . , also I'm using Windows Authontication
My problem now is when I try to create connection I have the following error
com.microsoft.sqlserver.jdbc.SQLServerException:
The TCP/IP connection to the host
localhost, port 1433 has failed.
Error: Connection refused: connect.
Please verify the connection
properties and check that a SQL Server
instance is running on the host and
accepting TCP/IP connections at the
port, and that no firewall is blocking
TCP connections to the port. at
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:130)
I don't know what is the exact problem here
If any one can help I will be appreciated
Thanks in Advance
That's caused by many probabilities like
1- IP is worong
2- Port is wrong
3- There is firewall prevent machine to go out and connect to another IP
4- SQL server down .
try to use
public class JdbcSQLServerDriverUrlExample
{
public static void main(String[] args)
{
Connection connection = null;
try
{
// the sql server driver string
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// the sql server url
String url = "jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE";
// get the sql server database connection
connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
// now do whatever you want to do with the connection
// ...
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
}
}
What i need to explain is there is very good technology called " Persistence " is better than JDBC and is more than brilliant and easy to use .
The problem is that your SQL server is either
not installed,
not running or
not accepting TCP/IP connections.
Particularly the last one is nasty, as I remember that some versions of SQL Server have not configured the TCP/IP connector to run by default.
Well first and foremost we need to see your code. Second looking at the error message the database is A)not running
B) on a different port
or C) the code is incorrect.
I am trying to create a JSF application using the Eclipse IDE. I am using a remote mySQL server as my database. How do I connect to this remote database for creating tables and accessing them?
Just supply the IP / hostname of the remote machine in your database connection string, instead of localhost. For example:
jdbc:mysql://192.168.15.25:3306/yourdatabase
Make sure there is no firewall blocking the access to port 3306
Also, make sure the user you are connecting with is allowed to connect from this particular hostname. For development environments it is safe to do this by 'username'#'%'. Check the user creation manual and the GRANT manual.
You need to pass IP/hostname of the rempote machine in the connection string.
import java.sql.*;
import javax.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String url = "jdbc:mysql://localhost:3306/mydb";
Class.forName ("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (url,"root"," ");
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
to access database from remote machine , you need to give grant all privileges to you data base.
run the following script to give permissions:
GRANT ALL PRIVILEGES ON . TO user#'%' IDENTIFIED BY 'password';
Plus, you should make sure the MySQL server's config (/etc/mysql/my.cnf, /etc/default/mysql on Debian) doesn't have "skip-networking" activated and is not binded exclusively to the loopback interface (127.0.0.1) but also to the interface/IP address you want connect to.
Create a new user in the schema ‘mysql’ (mysql.user)
Run this code in your mysql work space
“GRANT ALL ON . to user#'%'IDENTIFIED BY '';
Open the ‘3306’ port at the machine which is having the Data Base.
Control Panel ->
Windows Firewall ->
Advance Settings ->
Inbound Rules ->
New Rule ->
Port ->
Next ->
TCP & set port as 3306 ->
Next ->
Next ->
Next ->
Fill Name and Description ->
Finish ->
Try to check by a telnet msg on cmd including DB server's IP
Close all the connection which is open & connected to the server listen port, whatever it is from application or client side tool (navicat) or on running server (apache or weblogic). First close all connection then restart all tools MySQL,apache etc.
in my.cnf file , please change the following
## Instead of skip-networking the default is now to listen only on
## localhost which is more compatible and is not less secure.
## bind-address = 127.0.0.1
On Ubuntu, after creating localhost and '%' versions of the user, and granting appropriate access to database.tables for both, I had to comment out the 'bind-address' in /etc/mysql/mysql.conf.d/mysql.cnf and restart mysql as sudo.
bind-address = 127.0.0.1
Change the IP / hostname of the vps in your database connection string, instead of localhost. For example if my IP is 193.23.127.130:
jdbc:mysql://193.23.127.130:3306/yourdatabase
then make sure your vps firewall allow port 3306 for MySQL.
Then go to MySQL workbench, Server–Users and Privileges, create an account (in this case account: remoteUser, password:password), make sure Limit to Hosts Matching is % (means you can access from any other IP)
Then set password and grant rights then apply
then you can add the following code in Java to access remotely
Connection connection = DriverManager.getConnection("jdbc:mysql://193.23.127.130:3306/swing_demo", "remoteUser", "password");