I am trying to insert into a table without duplicates. I am using SQL derbyclient in Java. The code is not working (error with 'where not exists'). Any idea?
Connection connection = DriverManager.getConnection("jdbc:derby://localhost:1527/PetroleumDataStorageSystemDB;create=true");
PreparedStatement statement;
int i = 1;
int progress = 0;
for (Refuel refuelList1 : refuelList) {
progress = (i / refuelList.size()) * 100;
String sql = "INSERT INTO refuel (id_tank, time, fuel_volume, "
+ "refueling_speed) VALUES (?,?,?,?) "
+ "WHERE NOT EXISTS (SELECT * FROM refuel WHERE "
+ "id_tank = ? AND time = ? AND fuel_volume = ? AND "
+ "refueling_speed = ?)";
statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
statement.setInt(1, refuelList1.getTankID());
statement.setString(2, refuelList1.getTime());
statement.setDouble(3, refuelList1.getFuelVolume());
statement.setDouble(4, refuelList1.getRefuelingSpeed());
statement.execute();
i++;
}
The problem is how you build your query. That isnt a valid INSERT syntaxis
Try something like this on your db first with dummy values.
INSERT INTO refuel (id_tank, time, fuel_volume, refueling_speed)
SELECT ?, ?, ?, ?
FROM refuel
WHERE NOT EXISTS (SELECT
FROM refuel
WHERE
id_tank = ?
AND time = ?
AND fuel_volume = ?
AND refueling_speed = ?);
There are at least 8 question mark in your statement.
You have to set all of them!
After that you can check again and see if there are other errors.
You can't have a WHERE clause after a VALUES list.
Have a look here for valid Derby INSERT statement syntax.
Try something like this instead (notice the use of sysibm.sysdummy1, which guarantees that you only ever insert a single record at most. If you put an actual table name in there, you may potentially insert multiple records a time. Careful with that.):
INSERT INTO refuel (id_tank, tank, fuel_volume, refueling_speed)
SELECT ?, ?, ?, ?
FROM sysibm.sysdummy1
WHERE NOT EXISTS (SELECT *
FROM refuel
WHERE id_tank = ?
AND time = ?
AND fuel_volume = ?
AND refueling_speed = ?)
Also, as noted by Davide Lorenzo MARINO, make sure you set all the binding parameters correctly.
Related
I have written this code to add stuff to the database, however, when I try running it it does not work, i've been looking for ways to do it, but i just cant seem to find the solution, can anyone help?
String mySQL ="INSERT INTO Measurement (Level, Time, Date, TankID)"+"VALUES (textField1, currentTime,currentDate,(SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
stmt.executeUpdate(mySQL);
Both your SQL and prepared statement are malformed. Try using an INSERT INTO ... SELECT here:
String sql = "INSERT INTO Measurement (Level, Time, Date, TankID) ";
sql += "SELECT ?, ?, ?, TankID ";
sql += "FROM Tanks ";
sql += "WHERE TankName = '2' AND Site_ID = '1'";
stmt.setString(1, textField1);
stmt.setString(2, currentTime); // not sure about the type here
stmt.setString(3, currentDate); // also not sure about the type
stmt.executeUpdate();
Note that I am unsure about both the Java and SQL binding types of the columns for currentTime and currentDate. If not string, then the above would have to change slightly.
You should be using PreparedStatement to properly set the first parameter of the insert query and check the documentation of your DB server to use existing functions to get current time and date.
For example, mySQL has functions CURDATE() and CURTIME()
String query = "INSERT INTO Measurement (Level, Time, Date, TankID) "
+ "VALUES (?, CURTIME(), CURDATE(), (SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, textField1); // could be textField1.getText() or textField1.getValue()
statement.executeUpdate();
}
Based on your Database type change the connection details
Follow this Link for creating JDBC Connection and Inserting data
If you did the above steps please ignore this..
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.
I'm working with a MySQL-Server and I'm trying to select an ID from another table and insert that ID in a table but it doesn't work all the time.
Code:
public void submit() throws Exception {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
Statement stmt1 = connection.createStatement();
ResultSet asset_id = stmt.executeQuery("SELECT id FROM cars.asset_type WHERE asset_type.name =" + "'" + sellables.getValue()+ "'");
while (asset_id.next()) {
System.out.println(asset_id.getInt("id"));
}
double value = parseDouble(purchased.getText());
System.out.println(value);
LocalDate localDate = purchased_at.getValue();
String insert = "INSERT INTO asset (type_id, purchase_price, purchased_at) VALUES ('"+ asset_id + "','" + value +"','" + localDate +"')";
stmt1.executeUpdate(insert);
}
I keep getting the same error message.
Caused by: java.sql.SQLException: Incorrect integer value: 'com.mysql.cj.jdbc.result.ResultSetImpl#1779d92' for column 'type_id' at row 1
There's no value in doing two client/server roundtrips in your case, so use a single statement instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
If you really want to insert only the last ID from your SELECT query (as you were iterating the SELECT result and throwing away all the other IDs), then use this query instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
ORDER BY id DESC -- I guess? Specify your preferred ordering here
LIMIT 1
Or with the JDBC code around it:
try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO asset (type_id, purchase_price, purchased_at) " +
"SELECT id, ?, ? " +
"FROM cars.asset_type " +
"WHERE asset_type.name = ?")) {
s.setDouble(1, parseDouble(purchased.getText()));
s.setDate(2, Date.valueOf(purchased_at.getValue()));
s.setString(3, sellables.getValue());
}
This is using a PreparedStatement, which will prevent SQL injection and syntax errors like the one you're getting. At this point, I really really recommend you read about these topics!
String insert = "UPDATE PPN_WORKFLOW SET P1_F_Date = ?, SET P1_Completed = ?, SET C2_S_Date = ? WHERE ERF_No = ?";
stmt = conn.prepareStatement(insert);
stmt.setDate(1, date);
stmt.setInt(2, 1);
stmt.setDate(3, date);
stmt.setInt(4, erf_no);
stmt.executeUpdate();
I am trying to update a statement, but I am recieving this error
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3148)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(JdbcOdbcPreparedStatement.java:215)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(JdbcOdbcPreparedStatement.java:137)
at Mails.MailtoERF.check(MailtoERF.java:60)
at Mails.MailtoERF.main(MailtoERF.java:122)
you can not set like that .you need to change syntax.One time SET is enough
UPDATE PPN_WORKFLOW SET P1_F_Date = ?, P1_Completed = ?..... where condition
You have a SET for each Column name, you need to separate columns with comma only and use SET only once, see syntax here:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
You dont need SET for each column:
MySQL UPDATE SYNTAX:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
String insert = "UPDATE PPN_WORKFLOW SET P1_F_Date = ?, P1_Completed = ?,
C2_S_Date = ? WHERE ERF_No = ?";
Your Sql Update statement syntax is wrong.Do put 'SET' for each column in the query, you only do it at the first column
change it to
String insert = "UPDATE PPN_WORKFLOW SET P1_F_Date = ?, P1_Completed = ?, C2_S_Date = ? WHERE ERF_No = ?";
stmt = conn.prepareStatement(insert);
stmt.setDate(1, date);
stmt.setInt(2, 1);
stmt.setDate(3, date);
stmt.setInt(4, erf_no);
stmt.executeUpdate();
Heres the syntax for you reference
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.