I'm a java beginner and I'm working on a simple application which connects to a remote mysql database using JDBC. I've tested it locally and it works just fine, however I cannot get it to work on for my remote server.
I don't think its of much use but heres the code:
Connection connection = null;
String dburl = "jdbc:mysql://314159265:3306/Db_Name";
String userName = "user";
String passWord = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dburl, userName, passWord);
Statement st = connection.createStatement();
String query = "INSERT INTO Example (`TestColumn`) VALUES('hello')";
int rsI = st.executeUpdate(query);
System.out.println("Hi");
}catch (Exception e) {
System.out.println(e);
} finally {
if (connection != null) {
try {
connection.close();
System.out.println("Database connection terminated");
} catch (Exception e) { /* ignore close errors */ }
}
}
When I run this, I get the following message:
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.
I'm pretty sure it must be some kind of server configuration issue.
Notes:
Username, password, IP, database name, etc. are just examples.
This could be a firewall problem, or a configuration problem. But I don't think it is a coding problem at all - you need to start troubleshooting the connection.
Trouble shoot by attempting to use third party client apps to connect to mysql. This will indicate whether it is configured for external access. Although it doesn't ensure that JDBC is visible from the outside, it does rule out some potential firewall problems.
Follow this guide to help you mess with your configurations
Remote MYSQL Database Access
If you are still stuck, it could be a coding problem so check out this page:
How to connent to a remote mysql database with java?
P.S. I am assuming you are using unix as the operating system.
I guess 314159265 could be replaced by some address....
like jdbc:mysql://localhost:3306/
or jdbc:mysql://127.0.0.1:3306/
Related
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 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
i ran into a weird problem when connecting to mysql using java.
i'm running xampp with tomcat
i tried connecting to mysql from java. on my machine it works fine, but on a friends machine i get an error: access denied for user 'tomcat'#'localhost'
thing is - i managed to connect with the exact same info using php.
the java code for the connection is:
String url = "jdbc:mysql://localhost:3306/";
String dbName = "mta_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "tomcat";
String password = "tomcat";
try {
Class.forName(driver).newInstance();
_conn = DriverManager.getConnection(url + dbName, userName, password);
} catch (Exception e) {
e.printStackTrace();
}
port is fine
any idea what could be the cause?
The error is probably on the MySQL side, that is, the tomcat user doesnt have privileges to connect from non-localhost.
For simplicities sake you can first create an account that is able to connect from anywhere, via the MySQL GRANT statement like so:
GRANT ALL ON mta_db.* to tomcat#'%' identified by 'yourpassword';
In this case the % is a wildcard for any host.
If you know the actual IPs of your connecting clients you can later crack it down, to be more security conscious.
I try to connect to the database with this code:
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
String url = "jdbc:derby://localhost:1527/sample";
Connection con = DriverManager.getConnection(url);
PreparedStatement pstmt=con.prepareStatement("insert into app.discount_code values('A',22)");
pstmt.executeUpdate();
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
..but not result. What do I need to do to connect to the DB?
Sir, You are connecting to derby network server. So you need to firstly config the environment and start the network server. Please also check the jdbc driver jars are correct.
About how to config and start derby network server.Look at here.
http://db.apache.org/derby/papers/DerbyTut/ns_intro.html#ns_config_env
Also you'd better put the close method in your finally block.
You'd better paste your error message, it wil be helpful to find your problem.
I ve installed MySQL (last update).
I need to code, that ll create & establish a connection with SQL DB
& manage the DB(using SELECT, INSERT, CREATE).
I did everything but, I am not able to create connection. I've also installed the MySQL/J connector, I just extracted the .zip pack in a folder & added the folder path in Variables).
Can anyone tell me wat is meant by URL in the below line?
Connection connection = DriverManager.getConnection(url, username, password);
I ve tried this:
String url = "jdbc:odbc:sqlserver://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
But it's not working. I am unable able to understand the term 'URL'.
Can anyone explain, the meaning of 'url' and wat should be done to connect to a SQL server from Java.
Update:
This is the Full code. It still cannot connect.
import java.sql.*;
public class TestDriver {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//This s wat actually i did for connection
System.out.println("Driver Loaded Succesfully");
}
catch (Exception e){
System.out.println("Unable to Load Driver!!!");
}
try {
Class.forName(com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
System.out.println("connection Established");
}
catch(Exception e) {
System.out.println("Couldnt get connection");
}
}
}
Can you tell me wat is the purpose of MySQL Connector/J?
In the question you seem to be using a MySQL jdbc driver with a SQL Server jdbc URL. This won't work.
If you are using a MySQL database:
Class.forName("com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
If you are using a SQL Server database you are going to need a completely different jdbc driver. jTDS is open source and a good option. Include the jtds.jar file in your classpath and use something like:
Class.forName("net.sourceforge.jtds.jdbc.Driver"); // initialise the driver
String url = "jdbc:jtds:sqlserver://localhost:1433/myfirstdb";
Here's an extract from your code:
} catch (Exception e) {
System.out.println("Couldnt get connection");
}
You should never suppress exceptions as long as you don't understand its cause. Replace it by at least:
} catch (Exception e) {
System.out.println("Could not get connection");
e.printStackTrace();
}
Or maybe
} catch (Exception e) {
throw new RuntimeException("Could not get connection", e);
}
Either way, you should see the exception type, message and trace. In your code snippet the possible exceptions are ClassNotFoundException and SQLException. The first one would mean that the driver is not properly placed in the classpath. The second one would mean that connection cannot be obtained. The exception message and/or trace should tell in detail about the underlying root cause of the problem.
You should always observe exceptions. They tell something about the cause of the problem. You know, once a cause is understood, the solution is nothing more than obvious :)
See also:
Short MySQL/JDBC tutorial - Contains explanation about exception causes.
Further,
Can anyone tell me wat is meant by URL in the below line?
An URL is an Uniform Resource Locator. It's a common way to locate (identify) unique resources in computer systems and networks. The URL syntax for the MySQL database is explained in the documentation of the JDBC driver.
Can you tell me wat is the purpose of MySQL Connector/J?
It's the JDBC driver. The JDBC API exist of almost only interfaces. The DB vendors should provide their own concrete JDBC API implementation, which is the JDBC driver. With a JDBC driver you'll be able to connect a specific database using JDBC API.
If its MS SQL Server,
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");
For more info, see this to get started with Microsoft JDBC.
You can use any of the two JDBC drivers for MSSQL:
Microsoft SQL Server JDBC Driver
2.0
jTDS
For MS SQL Server driver 2.0, use
URL: jdbc:sqlserver://server:port; DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
For MySql & Java, see this on SO.
You forgot a " at Class.forName(com.mysql.jdbc.Driver");
It should be
Class.forName("com.mysql.jdbc.Driver");