I’m using the following codes to add a user to a table called USERS in my database, the connection is correct because I have tried other queries and they worked, I tried this query in Oracle itself and it worked, I’m just having problems with queries in java, mostly because of SPACE and the syntax, what is wrong with this one?
try
{
stmt=conn.createStatement();
//query="INSERT INTO Users (user_id,username,password,first_name,last_name) " + " VALUES (seq_users.nextval,'"+usernameCreateField.getText()+"','"+new String(passwordCreateField.getPassword())+"','"+firstnameCreateField.getText()+"','"+lastnameCreateField.getText()+"') ";
query="INSERT INTO Users (user_id,username,password,first_name,last_name) " +" VALUES (seq_users.nextval,'test','test','test','test') ";
rset=stmt.executeQuery(query);
}
catch(SQLException | NumberFormatException e)
{
System.out.println("result error, " +e.getMessage());
}
finally
{
try
{
rset.close();
stmt.close();
}
catch(Exception e)
{
System.out.println("Error in closing "+e.getMessage());
}
}
So problem is that you calling
executeQuery(query)on your statement and this is reason why it doesn’t work.executeQuery()method you cannot use for DML (Data Manipulation Language) statements like areINSERT,UPDATEandDELETE. For these statementsJavaoffers method namedexecuteUpdate()which exists for these DML statements.From the docs:
So only replace actual method with this and it would will work.
And sorry for my curiosity but why you aren’t using parametrized
SQLstatements? You would know that not using parametrized statements there is hight danger of SQL Injection and many hackers using this for damage databases. You should think about it. It is very important if you want to your database will be more safer. You wouldn’t believe what prove SQL Injection with database.Only for example for you, should create query like this:
This
?char is representing one parameter. Numbering starts with 1,2,3, etc.. not from zero.And then you must replace there params with real data before you
executestatement like this:So more about SQL Injection: here and here
EDIT:
I forgot to tell you when i just watching your code, when you opens
connectionand then of course you will close it, you not must callclose()method forstatementsorResultSet, all will be closed after when you closeconnection.Hope that helps you.
Regards