Unable to reopen MySQL connection in Java - java

I've got an annoying bug in Java. I'm connecting to a MySQL database and using Tomcat in Eclipse. It works brilliantly, but only the first time around. If I reload the page or run the page again, I get a com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
This is my code:
Connection conn = null;
String returnString = null;
Response response = null;
ResultSet rs = null;
try {
System.out.println("Trying to connect");
conn = DbUtil.getConnection(); // Connect to the database
System.out.println("Okay, connected");
query = conn.prepareStatement("SELECT host_firstname FROM host"); //Crashes at this line!
rs = query.executeQuery();
ConvertToJson jsonConverter = new ConvertToJson();
JSONArray jsonArray = new JSONArray();
jsonArray = jsonConverter.convertToJsonArray(rs);
returnString = jsonArray.toString();
response = Response.ok(returnString).build();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("hello!!!!");
}
finally {
if (rs != null){
rs.close();
}
if (query != null) {
query.close();
}
if (conn != null) {
conn.close();
}
}
return response;
I've seen everywhere I've Googled that I have to close the result set, the prepared statement and the connection (in that order) but once I've closed the connection, I can't reopen it.
This is my DbUtil class:
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null) {
return connection;
}
else {
try {
Properties prop = new Properties();
InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connection;
}
Any idea what is causing this problem?
Thanks
Omar :)

This answer is just to get your code working. But the best way would be to configure a connection pool. You should look about it.
YOur condition is :
if (connection != null) {
return connection; It's returning a closed connection
}
Try changing it to:
if (connection != null && !connection.isClosed()) {
return connection;
}

Related

Data source rejected establishment of connection, message from server: "Too many connections" java

I have a api executing several requests in mysql,
I launched this method several times, an error message is displayed too many connection, I try to close each time the connection after the execution of query but its not solving my problem
#PostMapping(value="/checkSql")
public ArrayList ExecuteSql(#RequestBody SQLBody sqlBody) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList array = new ArrayList();
DataSource datatsource = dataSource( sqlBody.getUsername(),sqlBody.getPassword(),sqlBody.getUrl(),sqlBody.getDriver());
try {
List<Fonctionnalite> listFonctionalite = findAllMP();
for( Fonctionnalite item : listFonctionalite) {
con = datatsource.getConnection();
stmt = con.createStatement();
FileReader fr=new FileReader("C:\\Users\\jihed\\OneDrive\\Bureau\\versionfinalPfe2020\\f2\\"+item.getName()+"\\"+item.getFileChek());
int i;
StringBuffer sb = new StringBuffer();
while((i=fr.read())!=-1) {
sb.append((char)i);
}
System.out.println(sb);
fr.close();
rs = stmt.executeQuery(sb.toString());
ResponseChek check = new ResponseChek(item.getId(),item.getName(),item.getDesscription(),item.getFileActivation(),item.getFilaDesactivation(),item.getFileChek(),1);
array.add(check);
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
}
} catch (SQLException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
if(datatsource != null) datatsource = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
return array;
}

Why don't work on the device and work on the simulator?

I'm making an app that access a mysql DB. I'm using direct JDBC, not web service. The simulator access with no problem but the real device give the error
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
This is the code of the connection class (its only the connection method)
public static Connection CONN(String name) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
conn = DriverManager.getConnection(url, un, password);
String stsql = "Select version()";
Toaster.toast(name);
//conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
Toaster.toast(se.getMessage());
System.out.println( se.getMessage() );
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
Can someone gives me some help?
Thanks!

Google cloud platform returning no content

Im making a REST Api using JAX RS and Google Cloud Platform, however when i test the api I get HTTP204 no content returned, I think it could be to do with my database connection but no matter what I change it doesnt fix it
#Override
public Response getAllStaff() {
ArrayList<StaffInfo> staffArray = new ArrayList<>();
Response response = null;
String url = null;
try {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver").newInstance();
url = "jdbc:google:mysql://{project-id}:staff-database/staffDatabase";
}
// Connection conn = DriverManager.getConnection(
// "jdbc:google:mysql://your-project-id:your-instance- name/database",
// "user", "password");
Connection conn = DriverManager.getConnection(url, "michael", "password");
Statement st = conn.createStatement();
String sql = ("SELECT * FROM StaffTable;");
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
staffArray.add(new StaffInfo(rs.getInt(0),
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5)));
}
GenericEntity<ArrayList<StaffInfo>> entity =
new GenericEntity<ArrayList<StaffInfo>>(staffArray) {};
response = Response.ok(entity).build();
// response = Response.ok(entity, MediaType)
conn.close();
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
I get no error messages just that there is no content returned
Here is what i see on cloud platform sql
and when i click on "staff-database"
Make sure the IP address of the machine from which you are making the call is authorized. You will find it in the "Access Control" tab of Cloud SQL.

while inserting data in SQLite :No such table exception

I am trying to insert data into sqlite table but it is giving me exception no such exception.please check my code and let me what changes should i make?
static Connection con;
public static Connection getConnection()
{
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:/home/zack/another.db");
con.setAutoCommit(false);
System.out.println("Opened database successfully");
}
catch(Exception e)
{
System.out.println("EXCEPTION IN :: SqliteCon:"+e.getMessage());
}
return con;
}
and here is my insert command file.
public String execute()
{
BufferedReader br;
try {
Connection con = SqliteCon.getConnection();
Statement stmt = con.createStatement();
br = new BufferedReader(new FileReader(
"/home/Zack/Desktop/session.csv"));
String line;
while ((line = br.readLine()) != null) {
String[] value = line.split(","); // your seperator
stmt.executeUpdate("INSERT into sessionTab values('jack','pass','NYC'")
//later i will insert values from CSV file
br.close();
}
}
catch (Exception e) {
System.out.println("Exception in UploadData class");
e.printStackTrace();
}
return SUCCESS;
}
I also added jar file to WEB-INF/lib/ of my project
finally solved this issue!!!switched from sqliteman to Firefox sqlite plugin and changed extension of db file from .db to .sqlite.

About JDBC Connection

A very simple question but i'm newbie in Java. How can I do the connection with my SQL Server DataBase that are in my network ?
I made the download of the JDBC 4.0, associate the file in my project and I'm trying the follow code, but I don't know how can I do a reference to my database
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "what i put here ?";
Connection con = DriverManager.getConnection(connectionUrl, "sa", "testtest");
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/";
String db = "yourDB";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try {
Class.forName(driver);
Connection con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(true);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
DriverManager.getConnection("jdbc:sqlserver://url.com;database=dbname;user=username;password=test")
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
replace the url/username/password. This is the connectionstring for sql server

Categories

Resources