I updated my database from SQLite db to MySQL and I suddenly I get this error:
java.sql.SQLException: No operations allowed after statement closed.
public boolean isEnough(int quantity, String item) throws SQLException {
boolean enough = false;
PreparedStatement pst = null;
ResultSet rs = null;
String sql = "SELECT * FROM Stock WHERE Item_name='" + item + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
int temp = rs.getInt(3);
if (quantity > temp) {
stmt.close();
enough = false;
} else if (quantity <= temp) {
enough = true;
int updatedStock = temp - quantity;
String sql_1 = "UPDATE Stock SET Item_quantity ='" + updatedStock + "' WHERE Item_name ='" + item + "'";
stmt.executeUpdate(sql_1); //error here
String sql_2 = "SELECT * FROM Stock WHERE Item_name='" + item + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
System.out.println(rs);
if (rs.next()) {
int isZero = rs.getInt(3);
if (isZero == 0) {
String sql_3 = "DELETE FROM Stock WHERE Item_name = '" + item + "'";
stmt.executeUpdate(sql_3);
JOptionPane.showMessageDialog(this, "Order Added\nItem is now out of Stock and removed from Stock database automatically.");
}
}
}
}
stmt.close();
return enough;
}
I'm closing connection and statement after every update, but I have no idea how to fix this error. If I go back to SQLite db this error disappears. I'm new to MySQL, so pardon me if I'm doing something wrong.
Related
I am using JDBC and mySQL to do an application for a family. After logging in into the system, the user can register for a family account. By SQL statement, I want to ensure that the input they keyed in is not repeated and they can only register when the database have a NRIC of them individually. I am working with JDBC and implementing the SQL statement in Java also. For now my problem is the system does not validate the input the user keys in and let's the information to be passed to database easily. Would appreciate some help!
*NRIC = Identity Card No
Snapshots of Database:
User Database
Family Account Database
Code
public boolean regFamily(FamilyAccount myFam, Customer myCust) throws Exception {
int fid = 0;
try {
String selectStatement2 = "SELECT * from familyok.user where nric = ? and familyid is NOT NULL ";
PreparedStatement pStmt2 = con.prepareStatement(selectStatement2);
pStmt2.setString(1, myCust.getNric());
ResultSet rs2 = pStmt2.executeQuery();
if (rs2.next()) {
String insertStatement = "Insert into familyok.familyaccount (familyname, fnric1, fnric2, fnric3)";
insertStatement = insertStatement + "values (?,?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, myFam.getFamilyname());
prepStmt.setString(2, myFam.getFnric1());
prepStmt.setString(3, myFam.getFnric2());
prepStmt.setString(4, myFam.getFnric3());
int status = prepStmt.executeUpdate();
if (status != 0) {
String selectStatement = "SELECT fid FROM familyok.familyaccount WHERE fnric1=?";
PreparedStatement pStmt = con.prepareStatement(selectStatement);
pStmt.setString(1, myFam.getFnric1());
ResultSet rs = pStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("fid") + "\t");
fid = rs.getInt("fid");
String updateStatement = "update familyok.user set familyid=?, familyname1=? where nric in (?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(updateStatement);
preparedStmt.setInt(1, fid);
preparedStmt.setString(2, myFam.getFamilyname());
preparedStmt.setString(3, myFam.getFnric1());
preparedStmt.setString(4, myFam.getFnric2());
preparedStmt.setString(5, myFam.getFnric3());
int status2 = preparedStmt.executeUpdate();
System.out.println("update=" + preparedStmt.toString());
if (status2 != 0) {
System.out.println("Family Account Created");
return true;
}
}
}
}
else
{
System.out.println("Can't Register");
return false;
}
} catch (Exception ex) {
throw new Exception("Error: " + ex.getMessage());
}
return false;
}
This question already has answers here:
Java JDBC MySQL exception: "Operation not allowed after ResultSet closed"
(2 answers)
Closed 6 years ago.
I am trying to run following code but getting error:
SQL Exception thrown: java.sql.SQLException: Operation not allowed
after ResultSet closed.
How to resolve this error? I need two result sets for my application.
public static void main(String[] args) {
String connectionUrl = "jdbc:mysql://127.0.0.1:3306/test";
String dbUser = "root";
String dbPwd = "Syntel#92";
Connection conn;
ResultSet rs, res1 = null;
Statement stmt = null;
int rowcount = 0;
// String queryString = "create table job_status_table as select j1.job_id,s1.Source_ID,s1.Source_name from JOb_list j1,SOURCE_DETAILS s1 where s1.Source_ID = j1.Source_ID";
String queryString = "create table job_status_table as select source_id,source_name from source_details";
String addcolumn = "alter table job_status_table add column Source_rowcount int";
String fetchdata = "Select Source_name from job_status_table";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
stmt = conn.createStatement();
// get record count from table job_status_table1
// stmt.executeQuery("select count() from job_status_table1");
// create table
stmt.executeUpdate(queryString);
System.out.println("Table created in the database");
stmt.executeUpdate(addcolumn);
System.out.println("alter table");
rs = stmt.executeQuery(fetchdata);
System.out.println("fetch data");
while (rs.next()) {
String table_count = null;
String table_name = null;
table_name = rs.getString("Source_name");
System.out.println(table_name);
// table_name = rs.getString("Source_name");
//System.out.println(table_name);
//rs.close();
table_count = "select count(*) from " + table_name;
//table_count = "select count(*) from " + table_name;
//rs.close();
// res1 = stmt.executeQuery(table_count);
res1 = stmt.executeQuery(table_count);
//System.out.print(res1);
if (res1.next()) {
rowcount = res1.getInt(1);//res1.getInt(1);
System.out.println("Result set values" + rowcount);
} else {
System.out.println("value is not present in resultset");
}
System.out.println("Get Row Count");
System.out.println(table_count);
// int cnt = rcnt(table_count);
String updaterow = "update job_status_table set Source_rowcount ="
+ rowcount
+ " where Source_name = '"
+ table_name
+ "'";
System.out.println("updateoutput" +stmt.executeUpdate(updaterow));
System.out.println("Update Complete");
}
/* if (conn != null) {
rs.close();
res1.close();
stmt.close();
conn.close();
conn = null;
}
*/
}
catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}**
You could try this:
First copy the ResultSet rs in an ArrayList and close it.
Iterate over the ArrayList and close res1 before the update.
And I don't think the else with "value is not present in resultset" is reachable, but if you should set the rowcount to 0.
EDIT
After reading the referenced question the second time:
The problem is the reusing of stmt for res1 and the update
I have problem with SQL query in JAVA.
JAVA code:
public boolean zeKontrolaExistujiciZalohyTest(String datum) {
try {
connected();
boolean existujeZaloha = false;
int pocet;
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
rs.next();
pocet = rs.getInt(1);
rs.close();
closed();
if (pocet >= 0) {
existujeZaloha = true;
} else {
existujeZaloha = false;
}
return existujeZaloha;
} catch (Exception e) {
e.printStackTrace();
Dialogs.create()
.title("Exception Dialog")
.showException(e);
return true;
}
}
SQL query in SQL Developer:
SELECT count(id) FROM pbtest.u_zalohy_energie
WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('15.09.2014', 'dd.mm.yyyy'), 'mm.yyyy');
When I run JAVA code, so result a variable is "pocet = 0". But, when I run SQL query in any the SQL Developer, so result column COUNT(id) is "1".
When I do change the SQL query, let me run JAVA code retuns a variable "pocet = 1".
Change sql code:
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE datum = TO_DATE('"+datum+"', 'dd.mm.yyyy')");
Does anyone know where is the problem?
For information: I use an Oracle database.
Thank you.
datum is string
SELECT count(id)
FROM pbtest.u_zalohy_energie
WHERE TO_DATE(datum, 'dd.mm.yyyy') = TO_DATE('15.09.2014', 'dd.mm.yyyy');
datum is date
SELECT count(id)
FROM pbtest.u_zalohy_energie
WHERE TRUNC(datum) = TO_DATE('15.09.2014', 'dd.mm.yyyy');
If datum is date, it might contain time component too. So remove it. using TRUNC()
TRUNC(datum) = TO_DATE('15.09.2014', 'dd.mm.yyyy');
Java code:
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TRUNC(datum) = TO_DATE('"+datum+"', 'dd.mm.yyyy')");
As a side note, use PreparedStatement and bind variables to avoid SQL*Injection
Your statement has a syntax error
ResultSet rs = statement.executeQuery("SELECT count(id) FROM "+table_ze+"\n" +
"WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
the executed query would be
SELECT count(id) FROM pbtest.u_zalohy_energie\nWHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('15.09.2014'', 'dd.mm.yyyy'), 'mm.yyyy')")
You should remove the "\n" as this will not lead in a line break.
Try it as
ResultSet rs = statement.executeQuery("SELECT count(id) FROM " + table_ze
+ " WHERE TO_CHAR(TO_DATE(datum, 'dd.mm.yyyy'), 'mm.yyyy') = TO_CHAR(TO_DATE('"+datum+"', 'dd.mm.yyyy'), 'mm.yyyy')");
Take also into consideration the comment from Maheswaran Ravisankar about: "... PreparedStatement and bind variables to avoid SQL*Injection"
Thank you for your advice, I solved the problem as follows:
public boolean zeKontrolaExistujiciZalohy(String datum, String typZalohy, String zalohaNaMesic) {
connected();
boolean existujeZaloha = false;
int pocet = 0;
ResultSet rs;
PreparedStatement pstmt = null;
try{
statement = connection.createStatement();
String SQL = "SELECT count(id) AS pocet FROM " + table_ze + " WHERE (EXTRACT(MONTH FROM datum)) = (EXTRACT(MONTH FROM to_date(?, 'dd.mm.yyyy'))) "
+ "AND (EXTRACT(YEAR FROM datum)) = (EXTRACT(YEAR FROM to_date(?, 'dd.mm.yyyy')))"
+ "AND typ_zalohy = ? "
+ "AND zaloha_na_mesic = ? ";
pstmt = connection.prepareStatement(SQL);
pstmt.setString(1, datum);
pstmt.setString(2, datum);
pstmt.setString(3, typZalohy);
pstmt.setString(4, zalohaNaMesic);
rs = pstmt.executeQuery();
while(rs.next()){
pocet = rs.getInt("pocet");
}
rs.close();
if (pocet > 0) {
existujeZaloha = true;
} else {
existujeZaloha = false;
}
return existujeZaloha;
}
catch(SQLException ex){
Dialogs.create()
.title("Exception Dialog")
.showException(ex);
return true;
}
}
On this java method I am trying to get data from a ms-sql server. I am trying to get the int value from a column , Now the columns I am using are all int's but for some reason when i try pulling it as a INT I am getting a number format error saying that the column is a nvarchar. Not sure what is happening and when i ran the System.out I am noticing I am only pulling the column name but no data that the column has. Here is my method, I am not sure what I am doing wrong or what is missing from this. Any help will be greatly appreciated thank you.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
String type = getTypeOfTimeOff().replaceAll("\\s+","");
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = "SELECT ? FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getTypeOfTimeOff().replaceAll("\\s+",""));
preparedStatement.setString(2, getEmpName());
preparedStatement.setString(3, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
//int checker = rs.getInt(1);
String acheck = rs.getString(1);
System.out.println("TIME off the user has : " + acheck);
int checker = Integer.valueOf(acheck);
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int aCheck = rs.getInt("column name");
}
}catch(){}
like this
For some reason what i did was add an AS to my query along with adding a if statement to my code caused the resultset to work with my code and allowed me to pull numbers from my database. Thank you for your help. Here is the updated code i added if it helps anyone.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = null;
if(getTypeOfTimeOff().equalsIgnoreCase("Vacation Day"))
selectProject = "SELECT VacationDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Bonus Day"))
selectProject = "SELECT BonusDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Birthday Day"))
selectProject = "SELECT BirthdayDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
System.out.println("Query String : " + selectProject);
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getEmpName());
preparedStatement.setString(2, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
int checker = 0 ;
checker = rs.getInt("dayList");
System.out.println("Days the user has off are: " + checker );
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}
I have this code:
try {
Integer user = InformationService.authenticate(username, password, connection);
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC");
System.out.println("SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC");
while (rs.next()) {
Task p = new Task(rs.getString("title"), rs.getInt("id"), rs.getString("descriere"),
rs.getString("data"), rs.getInt("uid"), rs.getString("data_creare"), rs.getString("ora"),
rs.getInt("status"), rs.getString("priority"), rs.getInt("sters"), rs.getInt("id_parinte"),
rs.getInt("notify"), rs.getString("assigner"), rs.getInt("durata"), rs.getInt("project_id"));
System.out.println(p);
tasks.add(p);
}
The problem is that it returns only the first row, and if I run the query manually I get more results (16 total). Here's the output:
SELECT * FROM tasks WHERE uid = 4 ORDER BY title ASC
models.Task#164b9b8f
Any idea why this is happening?
May be you can improve the code a bit like below which will help you to quickly identify the issue.
int rowCount = 0;
try {
Integer user = InformationService.authenticate(username, password, connection);
Statement st = connection.createStatement();
String query = "SELECT * FROM tasks WHERE uid = " + user + " ORDER BY title ASC";
System.out.println(query);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
Task p = new Task(rs.getString("title"), rs.getInt("id"), rs.getString("descriere"),
rs.getString("data"), rs.getInt("uid"), rs.getString("data_creare"), rs.getString("ora"),
rs.getInt("status"), rs.getString("priority"), rs.getInt("sters"), rs.getInt("id_parinte"),
rs.getInt("notify"), rs.getString("assigner"), rs.getInt("durata"), rs.getInt("project_id"));
rowCount++;
System.out.println(rowCount + "." + p);
tasks.add(p);
}
} finally {
System.out.println("Number of records = " + rowCount);
}
In this approach you can clearly identify how many rows were iterated.