SQLException: executeQuery method can not be used for update - java

I am trying to insert user information taken from a registration form into Derby DB using a java servlet class.
I get connected to the DB on NetBeans right after the user clicks the submit button with the user's information filled out. Then it should run this method:
public void insertNewUser(String userName, String passWord, String lastName, String firstName, String age, char sex, String email) {
try {
stmt = conn.createStatement();
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES ('" + userName + "', '" + passWord + "', '" + lastName + "', '" + firstName + "', " + age + ", '" + sex + "', '" + email + "')";
System.out.println(insertNewUserSQL);
stmt.executeQuery(insertNewUserSQL);
stmt.close();
} catch(SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
But I keep getting the following exception:
java.sql.SQLException: executeQuery method can not be used for update.
What does this mean exactly?
The SQL command is correct as I can do it manually on NetBeans SQL Command window.
Are there restrictions for servlets or something I don't know about?
Thanks in advance!

Since you are inserting a record, you should be using executeUpdate() not executeQuery().
Here are some methods that are usually misused:
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may
be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns
the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which
must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement
that returns nothing, such as a DDL statement.
One more thing, your query is weak as it is vulnerable with SQL Injection. Please do parameterized by using PreparedStatement.
Sample Code Snippet:
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(insertNewUserSQL);
pstmt.setString(1, userName);
// ... repeat this step until the last parameter ....
pstmt.setString(7, email);
pstmt.executeUpdate();
Java PreparedStatement

To update values you need to use an updatable ResultSet, as follows:
ResultSet res = preparedStatement.executeQuery(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
res.first();
res.updateInt("id", 2);
res.updateRow();
Alternatively, you can use the executeUpdate method of statement, as follows:
statement.executeUpdate("update table set id = 2");

Related

Updating database record in Java by using executeUpdate() function

I'm trying to update record in mysql database using java.
This is my code:
Statement stmt = con.createStatement();
String sql = "";
JOptionPane.showMessageDialog(null, "test");
sql = "update users set email='" + email1.getText() + "' WHERE fullname='" + user1 + "'";
stmt.executeUpdate(sql);
stmt.close();
con.close();
I'm getting this error:
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after statement closed.

inserting new user object into JDBC through the servlet

Here is the code for my servlet which recieves username parameter from a registration form
String tusername=request.getParamater("un");
String dbURL="db.com";
String dbusername= "lc";
String dbpassword="lcpw";
Connection con=(Connection) DriverManager.getConnection(dbURL,dbusername,dbpassword);
Statement stmt= con.createStatement();
String query="SELECT * FROM users.username WHERE username=(tusername)";
ResultSet rs= stmt.executeQuery(query);
if(rs.next()==false){
//create new userobject with value of tusername
}
My question is how do I create a new user object with calue of tusername, would it be like so ?
if(rs.next()==false){
Statement stmt=con.createStatament();
String query="INSERT INTO user.username VALUE 'tusername'";
ResultSet rs= stmt.updateQuery(query);
}
I understand some of this might be archaic (such as not using a prepared statement) , I am just trying to better my understanding and I think I am having some small syntax issues, thanks :)
You should be using a NOT EXISTS query to do the insert, and also you should ideally be using a prepared statement:
String sql = "INSERT INTO user.username (username) ";
sql += "SELECT ? FROM dual WHERE NOT EXISTS (SELECT 1 FROM user.username WHERE username = ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, tusername);
ps.setString(2, tusername);
int result = ps.executeUpdate();
if (result > 0) {
System.out.println("Inserted new user " + tusername + " into username table";
}
else {
System.out.println("User " + tusername + " already exists; no new record was inserted");
}
I don't know what your actual database is. The above should work out of the box for MySQL and Oracle. It might need to be modified slightly for other databases.
An alternative to the above query would be to just use your current insert, but make the username column a (unique) primary key. In that case, any attempt to insert a duplicate would fail at the database level, probably resulting in an exception in your Java code. This would also be a more database agnostic approach.

java.sql.SQLSyntaxErrorExceptionORA-00933: SQL command not properly ended

I am using this query
sql=String.format("INSERT INTO PM_AM_ASSET_AUDIT(TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME)
SELECT TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME
FROM PM_AM_ASSET_MASTER where id ="+id);
preparedStatement = connection.prepareStatement(sql,new String[] {"ID"});
but, I got this exception
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
When I remove generated keys concept the query executes.
Newer use concatenation in your statements to prevent sql injection.
Try this case:
String sql = "INSERT INTO PM_AM_ASSET_AUDIT " +
" (TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME) " +
"SELECT TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME " +
"FROM PM_AM_ASSET_MASTER where id = ?";
preparedStatement = connection.prepareStatement(sql);
p.setString(1, id);

java.sql.SQLException: Column count doesn't match value count at row 1

The structure of my table:
id int AUTO_INCREMENT PRIMARY KEY
title text
url text
age int
Here's how I am trying to save data into this table:
PreparedStatement ps=con.prepareStatement("insert into table(title, url, age) values ('\"+title+\",\"+url+\",\"+age+\"')");
System.out.println("Connected database successfully..");
ps.executeUpdate();
But when I run the app, I get
java.sql.SQLException: Column count doesn't match value count at row 1
I guess the problem might be in the id column, how to solve it?
The problem is not the id column.
From the statement it looks like you have quotes around all columns. Therefore it seems to the SQL, that you have only one column
'"title","url","age"'
What you might want to have is
"insert into table(title, url, age) values ('" + title + "','" + url + "'," + age + ")"
or even better yet, since it is a prepared statement
"insert into table(title, url, age) values (?, ?, ?)"
Actually, you have a different problem (you're only passing one "value") -
PreparedStatement ps=con.prepareStatement("insert into table(title, url, age) "
+ "values (?,?,?)");
ps.setString(1, title);
ps.setString(2, url);
ps.setInt(3, age); // <-- at a guess!
You original query put all three values in one string '\"+title+\",\"+url+\",\"+age+\"'.
possible mistakes
you may be included + sign extra
check the DB column order and SQL query order
try the same input with prepared statement
check the DB name,table name,connecter
The following code worked for me -
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/ems","root","");
java.sql.Statement s = c.createStatement();
s.executeUpdate("INSERT INTO employee VALUES('','"+fullname+"','"+address+"','"+homephone+"','"+dob+"','"+mobile+"','"+martial+"','"+nic+"','"+title+"','"+department+"','"+basicsalary+"','"+nname+"','"+nrelationship+"','"+nmobile+"')");
JOptionPane.showMessageDialog(rootPane, "Saved!");
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(employeemanagement.class.getName()).log(Level.SEVERE, null, ex);
}

Java and MySQL INSERT

I have set up a program for an enterprise to handle their brochures(catalogo in spanish).
I ask the user via Swings for the data, and then use it to generate a query and insert it into my db.
Here is the code:
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);
st = con.createStatement();
String sql = "INSERT INTO `catalogos` (`id`, `name`, `keywords`) VALUES(" + catNumIn.getText() + ", '" + catNameIn.getText() + "', '" + catKeyIn.getText() + "');";
st.executeUpdate(sql);
So i would like to know what my error is. Thank you!
Are you committing your transaction? You've said setAutoCommit(false) after all. Could you try:
setAutoCommit(true);
instead of the line you currently have, or:
con.commit();
after your database update?
When you construct sql statement in your front end and have an error, the best approach is to print the variable and see if there is a problem with the values like single quotes,missing comma,etc

Categories