This question already has answers here:
Java using JDBC - Too many connections?
(3 answers)
Closed 5 years ago.
When I try to connect to the database for a query, there is an exception occurred.
"SQL Exception : com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
public class DBConnection {
public static java.sql.Connection connect() throws ClassNotFoundException {
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/dmr";
String username = "root";
String password = "root";
try {
// Establishing connection
con = DriverManager.getConnection(url,username,password);
}
catch (SQLException ex) {
System.out.println("SQL Exception : "+ ex);
}
if(con != null){
System.out.println("****CONNECT TO THE DATABASE*****");
}
else{
System.out.println("####NOT CONNECT TO THE DATABASE");
}
return con;
}
}
If you using the local installation of MySQL db then use the below commands to check the how many connection are currently open.
mysql> show status like 'Conn%';
mysql> show status like '%onn%';
To get process list use: mysql> show processlist;
You can kill the unnecessary connections.
If you are using a database server maintained by other party then get their help to check and kill the unnecessary connections. There is property in mySQL server to specify the max number of connection allowed. You have increase it if necessary.
On Java side, i think after you done with database operation you should call con.close in finally block. Am not sure if you are doing that.
"Too many connections" error comes because server connected maximum limit of connection which server can be donem so server can not connect to new client. for solve this problem you need to restart the database server.
Related
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 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 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'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/