Is there a way to combine statements 1 and 2 into 1 query? Thanks.
String statement1 = "UPDATE thing SET status = ? WHERE id = ?";
String statement2 = "UPDATE thing SET error_message = ? WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(statement1);
preparedStatement.setInt(1,status);
preparedStatement.setInt(2, id);
connection.prepareStatement(statement2);
preparedStatement.setInt(1,error_message);
preparedStatement.setInt(2, id);
Looks like you are trying to set 2 columns of same table for an ID. You can change the query like
"UPDATE thing SET status = ? ,error_message = ? WHERE id = ?"
Further more, if the 2 update statements are updating different tables, you can execute both in same transaction. In this way, you can be sure that the commit will take place if both the statement successfully updates the table. Check the example here
Do it like this:
String statement1 = "UPDATE thing SET status = ? ,error_message = ? WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(statement1);
preparedStatement.setInt(1,status);
preparedStatement.setInt(2,error_message);
preparedStatement.setInt(3, id);
preparedStatement.executeUpdate();
Related
I'm working in one quiz game. There is question maker window. Which works good for saving question. But when want update one of text Field and press save, than error is happening. something is wrong with syntax?!
void insertCell(String tableNamer, String column, String value, int id) throws ClassNotFoundException, SQLException{
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:file:C:/Users/Juris Puneiko/IdeaProjects/for_my_testings/src/sample/DB/Questions/For_Private/Easy", "Juris", "1");
PreparedStatement ps = conn.prepareStatement("UPDATE ? SET ? = ? where ID = ?");
ps.setString(1, tableNamer);
ps.setString(2, column);
ps.setString(3, value);
ps.setInt(4, id);
ps.executeUpdate();
ps.close();
conn.close();
}
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "UPDATE ?[*] SET ? = ? WHERE ID = ? "; expected "identifier"; SQL statement:
UPDATE ? SET ? = ? where ID = ? [42001-196]
What is this >>> [*]?
What does it mean?
String sql = "UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value);
ps.setInt(2, id);
ps.executeUpdate();
ps.close();
conn.close();
The placeholders can only be used for values in most SQL databases, not for identifiers like table or column names:
"UPDATE myTable SET myCol = ? where ID = ?" -- OK
"UPDATE ? SET ? = ? where ID = ?" -- not OK
The reason is that those parameters are also used for prepared statements, where you send the query to the database once, the database "prepares" the statement, and then you can use this prepared statement many times with different value parameters. this can improve DB performance because DB can compile and optimize the query and then use this processed form repeatedly - but to be able to do this, it needs to know names of the tables and columns involved.
To fix this, you only leave the ?s in for the values, and you concatenate the tableNamer and column manually:
"UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?"
Keep in mind though that by doing this, tableNamer and column are now potentially vulnerable to SQL injection. Make sure that you don't allow user to provide or affect them, or else sanitize the user input.
This sql query is not updating the database, instead returning error. Any suggestions?
PreparedStatement ps10 = con.prepareStatement("UPDATE payroll_system.payslip SET hours_worked = (SELECT SUM(Hours) FROM payroll_system.monthly_timesheet WHERE employeeID=?) WHERE employeeID=?");
ps10.setString(1, employee_id);
ps10.setString(2, employee_id);
ps10.executeUpdate();
monthly_timesheet table:
payslip table:
Insert don't have where clause
"INSERT INTO payroll_system.payslip(expense_claims)
WHERE employeeID=?
SELECT SUM(expense) FROM payroll_system.expense_master"
eventually you are looking for update?
or use
"INSERT INTO payroll_system.payslip(expense_claims)
SELECT SUM(expense) FROM payroll_system.expense_mast"
for update
PreparedStatement ps9 = con.prepareStatement("UPDATE payroll_system.payslip
SET expense_claims = (SELECT SUM(Expense)
FROM payroll_system.expense_master
WHERE employeeID=?) WHERE employeeID=?");
ps9.setString(1, employee_id);
ps9.setString(2, employee_id);
ps9.executeUpdate();
This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 7 years ago.
Is there a limit to PreparedStatement variables (?) or requirements for their placement?
I have a method that takes in the parameters to complete a PreparedStatement however, it throws a SQLException.
Here is the PreparedStatement I want to use:
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
When I add in the first and second variables it runs just fine. Here is the working PreparedStatement:
String update = "UPDATE Student SET First_Name = ? WHERE UserID = ?";
Is there a reason I cannot get the first statement to work?
The entire method:
public static void runUpdate(String givenID, String givenAttribute, String givenUpdate) throws SQLException
{
// Establish the connection with the database
Connection conn = SimpleDataSource.getConnection();
try
{
// Create a string with the SQL Update statement
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
// Make a Prepared Statement with the connection to the database
PreparedStatement stat = conn.prepareStatement(update);
try
{
// Set the statement with the given parameters
stat.setString(1, Utility.getType(givenID));
stat.setString(2, givenAttribute);
stat.setString(2, givenUpdate);
stat.setString(3, givenID);
// Execute the Update Statement
stat.executeUpdate();
}
finally
{
// Close the prepared Statement
stat.close();
}
}
finally
{
// Close the connection to the database
conn.close();
}
}
You can't use the query like this.
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
You should write the name of table and the name of the column like here.
String update = "UPDATE table SET column_name = ? WHERE UserID = ?";
You can use variables in prepared statements only as placeholder of literals in SQL statements. So you cannot use them for column name, or table names. For these you should resort to dynamic SQL statements.
Im trying to add the number 1 to a certain field. How could i manage to do that? Ive tried it but i can never get it to add 1. My ms access table column is set to Number not text.
if (s2.equals(box1Text)) {
if (s3.equals(box2Text)) {
if (s5.equals(currentWinner)) {
String sql = "UPDATE Table2 "+ "SET Score = ? " + "WHERE Better = '" + s1+"'";
PreparedStatement stmt = con.prepareStatement(sql);
//points made here
if (s4.equals(betScore)) {
stmt.setString(1, "+1");//how could i add 1 to the field?
stmt.executeUpdate();
} else {
}
First you do something that is regarded as bad practice : you construct your query by adding the value of a parameter in the string.
String sql = "UPDATE... >+ s1 +<..."
Please nether do that (what is between > and <) when programming seriouly, but allways use ? to pass values.
Second, SQL can do the job for you :
String sql = "UPDATE Table2 SET Score = Score + 1 WHERE Better = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, s1);
stmt.executeUpdate();
(try, catch, tests and other details omitted for brevity)
How can I use a prepared statement to delete entries from a database? I have found that I must write the following code
String deleteSQL = "DELETE DBUSER WHERE USER_ID = ?
but I want to specify a clause with more than one variable. I have used the AND operator but it doesn't seem to work.
Here is an example if your syntax is not correct..
DELETE DBUSER WHERE USER_ID = ? and USER_NAME = ?;
you can append more conditions in where clause by using more AND ... operators.
OR if you have more than one USER_IDs to delete in a single query..
DELETE DBUSER WHERE USER_ID in (?, ?, ?, ?);
It's must work/ for example
Select from Employee e where e.ID < ? and e.ID >= ? order by e.ID
to set values use this:
int id1 = 1;
int id2 = 10;
preparedStatement.setInt(2, id1);
preparedStatement.setInt(1, id2);
for delete I use this code:
public synchronized boolean deleteNewsById(Integer[] idList)
throws NewsManagerException {
DatabaseConnection connection = pool.getConnection();
StringBuffer buffer = new StringBuffer();
buffer.append("(");
buffer.append(idList[0]);
for (int i = 1; i < idList.length; i++) {
buffer.append(",");
buffer.append(idList[i]);
}
buffer.append(")");
PreparedStatement statement = connection
.getPreparedStatement(DELETE_NEWS_BY_ID + buffer);
}
and sql query looks like this
private static final String DELETE_NEWS_BY_ID = "delete from NEWS where ID in ";
or simple write delete from NEWS where ID in (?,?,?) and set values like in first example
I think the response from Aleksei Bulgak is correct, but to perhaps more straightforwardly word it...you can set your parameters like this:
String stmt = "DELETE DBUSER WHERE USER_ID = ? and (USER_NAME = ? or USER_NAME = ?)";
preparedStatement.setInt(1, firstParam);
preparedStatement.setString(2, secondParam);
preparedStatement.setString(3, thirdParam);
...and for however many parameters(question marks) in your SQL (no matter if you're using IN or whatever you want), you should set that many parameters here(using setInt for ints, setString for Strings, etc). This goes for select and delete queries.
Are you looking for the IN operator which allows you to specify multiple values in the WHERE clause such as in my example.
String deleteSQL = "DELETE DBUSER WHERE USER_ID IN (?)"
Though in PreparedStatement IN clause alternatives there are some useful answers and links that you may want to take a look at such as Batch Statements in JDBC which discuss the pros and cons of different batching approaches. The IN approach I'm suggesting is part of that discussion. The end result is that you make just one trip to the database, rather than one per delete and that's better performing because of the reduced network activity required.