How to connect to a remote MySQL database with Java? - java

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

Related

Mysql connecting ok with local host but not connecting with ip address

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.

The TCP/IP connection to the host localhost, port 1433 has failed error, need assistance

Full error I'm getting:
The TCP/IP connection to the host localhost, port 1433 has failed. Error: "connect timed out. 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.".
I have already checked that TCP/IP is enabled, using port 1433, and TCP dynamic ports is empty. I have disabled windows firewall.
Here is my code:
import java.sql.*;
public class DBConnect {
public static void main(String[] args) {
// TODO Auto-generated method stub
String dbURL = "jdbc:sqlserver://localhost:1433;DatabaseName=TestDB1;instance=SQLSERVER;encrypt=true;TrustServerCertificate=true;";
String user = "sa";
String pass = "";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection myConn = DriverManager.getConnection(dbURL, user, pass);
try {
Statement myStmt = myConn.createStatement();
try {
ResultSet myRs = myStmt.executeQuery("Select * from Login");
while (myRs.next())
{
System.out.println(myRs.getString("Username"));
System.out.println(myRs.getString("Password"));
}
}
catch (Exception e)
{
System.out.println("Error with query");
}
}
catch (Exception e)
{
System.out.println("Error connecting to database");
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Have you enabled 'Named Pipes' and 'TCP/IP'?
Open the 'Sql Server Configuration Manager' application.
In the left pane, go to 'SQL Server Network Configuration' -> 'Protocols for [instance-name]'
Right-click on both 'Named Pipes' and 'TCP/IP' and select 'enable'.
Have you used the correct port?
Double-click on 'TCP/IP'
Select 'IP Addresses' tab
Scroll to IPAII. Your port number is here.
Restart the 'SQL Server ([instance-name])' windows service.
This error usually come when SQL server not accepting TCP/IP Connection, pls try below steps it will work for sure.
1)open run and add command SQLServerManager15.msc
2)click on network configuration then "protocols for MSSQLSERVER"
3)Select protocol name - "TCP\IP" and make sure that it is enable if not then pls make it enable.
4)Check the property and find port in IP address tab.
Restart the server, it should work
And also make sure that on the same page TCP/IP is enabled
My solution:
Client: DBeaver
Auth: Windows Authentication
After taking the steps:
Enable tcp/ip
Enabling named pipes
Connection string: localhost\SQLEXPRESS (that backslash made all the difference).

Could not create connection to database server - java mysql connector

I can't connect to a mysql database on my "live-server" but it works just fine on my local computer.
In my main class I am doing this:
try {
main.connection.open();
} catch (SQLException e1) {
log.fatal(e1.getMessage());
System.exit(0);
}
And the open method looks like this
public void open() throws SQLException{
if(con != null) close();
con = DriverManager.getConnection(url, user, password);
}
After a couple of minutes running I am getting this:
14:35:47.434 [main] FATAL se.mypack.Server - Could not create connection to database server. Attempted reconnect 3 times. Giving up.
How do I debug this? The url, server and password variables is correct. What might be the problem here?
Using mysql-connector-java-5.1.29-bin.jar
First you have to make sure you have loaded your DB-driver class.
It goes as the following:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
This is for DERBY DB.
There is a different driver class for each DB, but the idea is the same.
If you already did it, check if you have a tcp connection to the DB server from the client machine
that tries to establish the connection. You can use : ping -t your.server.ip.
If you get a response, try to establish telet connection to that url + port number (the port that the DB listener listens to, for Oracle it will be 1521, for Derby it is 1527..) and see that you don't get any connection refuse messages.
If your connection attempt failed, see if the DB listener is up, or whether you have a fire wall issue.
Good Luck,
Yosi Lev

Unable to establish database connection to SQL Server 2008 using java in Eclipse IDE

I am trying to connect to HP Operations Manager Database using Java code in Eclipse IDE.
I am able to connect successfully through Microsoft SQL Server Management Studio 2008 but it fails through code.
I have installed "Microsoft JDBC Driver 4.0 for SQL Server"
Code:
import java.sql.*;
public class ConnectDatabase {
Connection dbConnection = null;
String dbName = "openview";
String serverip="10.105.219.102";
String serverport="1433";
String url = "jdbc:sqlserver://"+serverip+"\\OVOPS;databaseName="+dbName+"";
String userName = "HPOM-QA-WIN\\Administrator";
String password = "Nbv12345";
final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Statement statement = null;
ResultSet rs = null;
int updateQuery = 0;
public Connection getConnection() {
System.out.println(url);
try{
Class.forName(driverName).newInstance();
dbConnection = DriverManager.getConnection(url,userName,password);
System.out.println(DriverManager.getDrivers());
statement = dbConnection.createStatement();
String QueryString = "select Id from openview.dbo.OV_MS_Message where OriginalServiceId like '{FaultDn[1]}'";
updateQuery = statement.executeUpdate(QueryString);
if(updateQuery!=0){
System.out.println("success" + updateQuery);
}
statement.close();
dbConnection.close();
}catch (Exception e){
e.printStackTrace();
}
return dbConnection;
}
public static void main(String[] args) {
ConnectDatabase cDB = new ConnectDatabase();
cDB.getConnection();
}
}
I get the following error when I execute this code:
jdbc:sqlserver://10.105.219.102\OVOPS;databaseName=openview com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host 10.105.219.102, named instance ovops failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.getInstancePort(SQLServerConnection.java:3589)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.primaryPermissionCheck(SQLServerConnection.java:1225)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:972)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.ucs.test.ConnectDatabase.getConnection(ConnectDatabase.java:27)
at com.ucs.test.ConnectDatabase.main(ConnectDatabase.java:51)
When I change the url to
String url = "jdbc:sqlserver://"+serverip+"\\OVOPS:"+serverport+";databaseName="+dbName+"";
I get the below error:
jdbc:sqlserver://10.105.219.102\OVOPS:1433;databaseName=openview com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'HPOM-QA-WIN\Administrator'. ClientConnectionId:f1d323b7-9998-418c-b2a2-f2a7bd7b9b04
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:254)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:84)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2908)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.ucs.test.ConnectDatabase.getConnection(ConnectDatabase.java:27)
at com.ucs.test.ConnectDatabase.main(ConnectDatabase.java:51)
I have explicitly added an inbound rule in windows firewall to allow UPD traffic on 1434 port, then disabled the firewall. But I still get this error.
The credentials provided here are used for connection using Microsoft SQL Server Management Studio and it works perfectly fine. But it fails through the code.
I am not sure where I am going wrong. I am unable to establish a successful connection through the code. Please help me.
Hey Thanks all for your responses. Finally I was able to resolve the issue. The problem was with the url and auth dll. Changed the url to
"jdbc:sqlserver://10.105.219.102:1433;instance=OVOPS;DatabaseName=openview;integratedSecurity=true"
and added the location of "sqljdbc_auth.dll" in java.library.path. It worked!
Thanks again for your efforts to help me :)
It took me a while to sort this issue out, but you have to head into the SQL Server Configuration Manager application. When that's loaded, expand the [SQL Native Client 11.0 Configuration] > Client Protocols.
Enable all three (Shared Memory, TCP/IP, and Named Pipes), if they aren't already.
Then click on TCP/IP and ensure that the default port is 1433.
If you have a 32bit system or version of SQL Server installed, do the same in the SQL Native Client 11.0 Configuration (32it) menu, enabling Shared Memory, TCP/IP, and Named Pipes and setting the default port to 1433.
Then click open the [SQL Server Network Configuration] or (32bit if applicable), and select the [Protocols for "YOURSERVERNAME"].
Ensure again that Shared Memory, TCP/IP, and Named Pipes are all enabled.
Then click on the [TCP/IP] Protocol Name, then select the [IP Addresses] tab at the top of the new popup window. For IP1 ensure that Active is YES; Enabled is YES (this is No by default, even if it is Active); and set the TCP Port to 1433 (tbh I don't know if you have to do this step, but I did and it worked!!); my TCP Dynamic Ports are set to 0 and I didn't change any of the IP addresses;
I did the same thing for IP10, which has IP: 127.0.0.1, which is the local machine.
I also scrolled down to the bottom of the page, and set IPAll TCP Ports to 1433, (dynamic ports is 49163).
Then you need to Apply all changes, close the properties window, and click on SQL Server Services in SQL Server Configuration Manager, and restart all running Servers.
This should do it :D
Catch example:
String url = "jdbc:sqlserver://localhost:1433/databaseName";
String username = "user";
String password = "pass";
Connection connection = DriverManager.getConnection(url, username, password);
1433 is default port.
Dont use '\' in url.
This is probably not an answer to your question, but I hope this will help you. Here is the way how to properly return connection (mysql):
import java.sql.*;
public class ConnectToDatabase{
public Connection getConn(){
final String DBPATH="jdbc:mysql://localhost:3306/mydb";
final String DBUSER="root";
final String DBPASS="";
Connection conn=null;
try {
conn = DriverManager.getConnection(DBPATH,DBUSER,DBPASS);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
Try changing your database user password. Make sure new password doesn't have special characters.
I faced same problem and it got resolved after changing the db password.
Steps of my workaround:
I was getting sqlserverexception.java 190 error stating unable to connect to host port: 4500 which was my localhost port.
Opened Sql Server Configuration Manager -> SQL Server Network Configuration -> Protocols for MSSQLSERVER -> Enabled TCP/IP.
Checked TCP port number. It was 1433. So I changed 4500 to 1433 in my registry file.
After following above steps, I got a different error this time startingpassword for my db user(sql-test) is incorrect. I changed the password to sqltest123 and it worked.

JDBC Example for java

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.

Categories