Connecting to local Mysql server from other pc - java

I have an local server which installed apache and mysql servers. both of them works very well. I can display the apache default page on browser fine. And I can manage the mysql database via terminal. All okey for now. But if I try to write code to use my DB. It gives me communication link error.
Here is the simple JAVA code:
public static void main(String[] args) {
String url = "jdbc:mysql://192.168.1.49:3306/test";
String username = "root";
String password = "1234";
System.out.println("Connecting database...");
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
AND HERE IS THE ERROR:
Connecting database...
Exception in thread "main" java.lang.IllegalStateException: Cannot
connect the database! at
servermysql.ServerMysql.main(ServerMysql.java:34) Caused by:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
THE SERVER İS UBUNTU 14.04 SERVER
THANK YOU FRİENDS

You have to set MYSQL bind-address to 0.0.0.0 because it usually only listens on 127.0.0.1 by default executing following command:
sed -i -e”s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/” /etc/mysql/my.cnf
Or manually change the bind-address to 0.0.0.0 in /etc/mysql/my.cnf and restart MYSQL.

Related

How can I connect to db2 database remotely

I am using following java application to connect db2 database for localhost and code is:
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50000/sample";
String user="admin";
String password="admin";
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url, user, password);
stmt = connection.createStatement();
}
catch (SQLException e) {
e.printStackTrace();
}
The problem is that when application and db2 is running on the same machine, then it is working, but if db2 database is on another machine then it is not working. I am using ip in my url which is:
String url="jdbc:db2://192.168.1.68:50000/sample";
And it's giving the following error:
com.ibm.db2.jcc.am.DisconnectNonTransientConnectionException: [jcc][t4][2043][11550][3.59.81] Exception java.net.ConnectException: Error opening socket to server /192.168.1.64 on port 50,000 with message: Connection timed out: connect. ERRORCODE=-4499, SQLSTATE=08001
How can I connect to the database remotely?
Check if your private or public network firewall is on ?? If it is on then instead of doing it off make an inbound rule and then try to connect it with DB2 database from another system.

Connection refused: connect, can't connect database mysql

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.

how to embed oracle XE database in executable jar?

I have developed java application using java swings and oracle XE database in "myecplise". I have also created executable jar file and it runs fine in my pc but it is showing jdbc.odbc ClassNotFound exception and NullPointer Exception in other pc
my connection code is
import java.sql.*;
public class Connect {
static Connection con=null;
public static Connection ConnectDB(){
try{
// Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection("jdbc:oracle:thin:system/system#localhost");
return con;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
e.printStackTrace();
return null;
}
}
}
The DriverManager.getConnection("jdbc:oracle:thin:system/system#localhost") states that the driver manager will connect to the database located at your localhost. On the other PC it tries to locate the database on that other machine, since the database is not present there the exception will occur.
You have to change the connection to something like:
DriverManager.getConnection("jdbc:oracle:thin:#arg0:arg1:arg2", arg3, arg4);
Where
arg0: the IP of the machine that hosts the database.
arg1: The port that the database is listening to.
arg2: the SID of the database.
arg3: the schema username.
arg4: the schema password.

Make a connection to a MS SQL database in the local machine

I am trying to access a database which is located in my C drive in my local machine. I can access the data base through Microsoft SQL server Management Studio. However as the data base is not in a server my first question is "if even it's possible to access it through my java code."
-I have tried my local machine address and also the name of the server however non of them seems to be working.
String url = "jdbc:sqlserver://DAVE-PC\\SQLEXP/";
String dbName = "STORESQL";
// String driver = "com.mysql.jdbc.Driver";
String userName = "dave-PC\\dave";
String password="";
try {
// Class.forName(driver).newInstance();
Connection con =DriverManager.getConnection(url+dbName,userName,password);
java.sql.Statement stm= con.createStatement();
*DAVE-PC\SQLEXP/" is the name of my database. The username and password are windows authentication.
My second question is if I can't access the database like this, Is there any virtual server (compatible with microsoft SQL) that I can copy the database there and access it from the?
I think your mistake is in userName. for your PC you can try LOCALHOST or 127.0.0.1 Perhaps you would try this method to connect:
try{
server = "jdbc:sqlserver://127.0.0.1:1433;databaseName=STORESQL;selectMethod=cursor";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(server,"dave",password);
}catch(SQLException e){
System.out.println(e);
}catch(ClassNotFoundException e){
System.out.println(e);
}

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.

Categories