Java why appear MySQLNonTransientConnectionException: No operations allowed...? - java

I am writing application which work with database. I have such class for Connection to mysql database:
public class DataBaseConnector {
private static final String URL = "jdbc:mysql://localhost:3306/dataBase";
private static final String USER = "user";
private static final String PASSWORD = "password";
private Connection connection;
private static DataBaseConnector instance;
public synchronized static DataBaseConnector getInstance() {
if (instance == null) {
instance = new DataBaseConnector();
}
return instance;
}
private DataBaseConnector() {
}
public Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
System.out.println("Database connected!");
this.connection = connection;
return connection;
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
}
And test method which perform SQL query:
public static void main(String[] args) {
try {
Connection connection = DataBaseConnector.getInstance().openConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM hotel_administrators WHERE login=?");
stmt.setString(1, "lll");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
And I don't understand why appears such exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
Database connected!
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1187)
at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1182)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4035)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4004)
at model.DataBaseManager.main(DataBaseManager.java:81)
What's wrong?

When you create the connection you use a try-with-resources statement which automatically closes the new connection.
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
return connection;
}
/* this is automatically executed:
finally {
connection.close();
}
*/
Now when you execute the query MySQL simply complains that the connection was already closed. To avoid the error you could write:
try {
this.connection = DriverManager.getConnection(URL, USER, PASSWORD));
System.out.println("Database connected!");
return this.connection;
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}

Related

Unable to connect with MariaDB using Java

I am trying to connect with My company's database which is 'MariaDB', using Java, I am using following code:
package co.companyname.helpers;
import java.sql.*;
public class DatabaseConnectivity {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
String query = "select * from time_clock limit 10";
try {
Class.forName("org.mariadb.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(
"jdbc:mariadb://host_url:3306", "root", "password");
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = query;
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
At above I have used host_url, but I am using actual host within string, now I am getting following error:
java.lang.ClassNotFoundException: org.mariadb.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:315)
at co.company_name.helpers.DatabaseConnectivity.main(DatabaseConnectivity.java:10)
Goodbye!
I need to know, if I am doing anything wrong.
Thanks.

How to create a connection to the 2 Mysql servers?

I'm totally noob! I have automative test framework previously written for single Mysql server with 2 database on it. And DB connection was looked like
public static Connection getConnection() {
if (conn == null) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://"
+ PropertyHandler.getInstance().getValue(PropertyKeys.dbHost)
+ ":"
+ PropertyHandler.getInstance().getValue(PropertyKeys.dbPort),
PropertyHandler.getInstance().getValue(PropertyKeys.dbUser),
PropertyHandler.getInstance().getValue(PropertyKeys.dbPass));
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return conn;
}
public static void closeConnection() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
But now they are on different IPs . Please provide simple example how to fix it. Thanks.
Java DB connection is just a Object. you can create 2 connection Objects for 2 Mysql Servers.
you have getConnection() method created. so you just need to change the method to accept connection parameters.
for example:
Connection db1 = getConnection(server_ip, db, username, password);
Connection db2 = getConnection(server_ip2, db, username2, password2);
public static Connection getConnection(String ip, String db, String user, String pass) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://"+ip+"/"+db+"?" +
"user="+user+"&password="+pass);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return conn;
}

Fail to retrieve data from postgresql

this is my connection string for connection postgresql database .And using this code I am able to connect the db
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5433/Test", "youtube",
"1");
Then I am using the same code to retrieve some data .And I get this exception
org.postgresql.util.PSQLException: ERROR: "userdetail" NOT EXIST
Position: 27
which referr this line
con=GetDbConn();
So mytable name is UserDetail not userdetail I dont understand why am i getting this exception message
And this is my code
public class DbUtils {
private static final String DB_DRIVER="org.postgresql.Driver";
private static final String DB_CONN="jdbc:postgresql://127.0.0.1:5433/Test";
private static final String DB_USER="youtube";
private static final String DB_PASS="1";
public void SelectUserDetails() {
Connection con=null;
Statement statement;
String query="select isim,soyisim from UserDetail";
try {
con=GetDbConn();
statement= con.createStatement();
ResultSet resultSet=statement.executeQuery(query);
while(resultSet.next()){
String isimM=resultSet.getString("isim");
String soyisimM=resultSet.getString("soyisim");
System.out.println("isim :"+soyisimM+" soyisim: "+soyisimM);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static Connection GetDbConn() {
Connection con = null;
try {
Class.forName(DB_DRIVER);
con=DriverManager.getConnection(DB_CONN, DB_USER, DB_PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}

Null pointer exception after initialize

private static String dbURL = "jdbc:mysql://localhost:3306/mydb";
private static String username = "secret";
private static String password = "secret";
private static Connection conn = null;
public static void initDbConnection(){
try {
conn = DriverManager.getConnection(dbURL, username, password);
Class.forName("com.mysql.jdbc.Driver");
} catch (SQLException e1) {
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void test3(){
initDbConnection();
try{
String sql = "SELECT * FROM Products";
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()){
String name = result.getString("name");
System.out.println(name);
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
Why I'm getting null pointer exception on conn even though I called the initDbConnection() on test3() ? How will I elimate this problem?
Class.forName("com.mysql.jdbc.Driver");
should be the first line. As this load the mysql driver in the memory. Then you will acquire the connection.
So it should be
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, username, password);
} catch (SQLException e1) {
e1.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}

Returning the Connection from JDBC into a main method of Java?

Is it possible to return the type Connection?
And use it as a method passed by reference through out the program?
I find it makes the database interaction a lot easier if it is passed as a method.
public static Connection database(String database, String username, String password) {
String url = "jdbc:postgresql:" + database;
//LOAD DRIVER
try {
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
//CONNECT TO DATABASE
try {
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
db = database("java_jdbc", "admin", "fake_password_1234");
}
You can do that.
Just remember to invoke close() on the connection to release its resources when done.
package mySystem;
import java.sql.*;
import javax.swing.*;
public class MySqlConnector {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.jdbc.Driver"); //register jdbc driver
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/inventory_db", "root", "");
// JOptionPane.showMessageDialog(null, "Connected to db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}

Categories