I was writing a java code for authenticating and updating login credentials for my revenue reporting tool.
getName()
is the function for asking for users name and then cross checking my database for any duplicate entries and accordingly adding.
My problem is that when I provide a different name in the starting it works and adds the name to the database. But when I provide a duplicate name and then provide a different name it gives me this error:
Exception in thread "main" java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:804)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6986)
at database_console1.test2.getName(test2.java:67)
at database_console1.test2.getName(test2.java:74)
at database_console1.test2.getName(test2.java:74)
at database_console1.test2.getName(test2.java:74)
at database_console1.test2.getName(test2.java:74)
at database_console1.test2.getName(test2.java:74)
at database_console1.test2.main(test2.java:44)
Java Result: 1
BUILD SUCCESSFUL (total time: 20 seconds)
Here is my function.
public void getName() throws SQLException {
String sqla = "SELECT * FROM veuser where UserName = ?" ;
String sql = "INSERT INTO veuser (UserName) VALUES (?)";
boolean b = true;
while (b) {
System.out.println("Enter your username");
name = sc.nextLine();
if (!"".equals(name)) {
b = false;
} else {
System.out.println("Username cant be left blank");
}
}
ps = conn.prepareStatement(sqla);
ps.setString(1, name);
rs = ps.executeQuery();
while (rs.next()) {
String i = rs.getString(2);
System.out.println(i);
if (i.equals(name)) {
System.out.println("User already exists.Choose another username");
getName();
}
}
os = conn.prepareStatement(sql);
os.setString(1, name);
int row = os.executeUpdate();
if (row > 0){
System.out.println("Successfully added...");
ps.close();
os.close();
}