Reputation: 345
I'm using a prepared Statement to insert whit WHERE NOT EXISTS. I have tried different ways, but it simply doesn't work.
The error I catch with catch (SQLException sqle)
is
java.sql.SQLException: Error preparing query: No tables used
My code is:
try {
//hacer los inserts
sql = "INSERT INTO calendario (year, mes, dia, date) "
+ "SELECT * FROM (SELECT ? as year,? as mes ,? as dia,? as date) AS tmp "
+ "WHERE NOT EXISTS (SELECT * FROM calendario WHERE "
+ "year=? AND mes=? AND dia=?)";
injerto = conn.prepareStatement(sql);
injerto.setInt(1, year);
injerto.setInt(2, mes);
injerto.setInt(3, dia);
injerto.setDate(4, sqldate);
injerto.setInt(5, year);
injerto.setInt(6, mes);
injerto.setInt(7, dia);
injerto.addBatch();
injerto.executeBatch();
} catch (SQLException sqle) {
sqle.printStackTrace();
System.out.println("Calendario dice: me muero");
System.exit(0);
}
I'm using MariaDB, which print this error:
Caused by: org.mariadb.jdbc.internal.util.dao.QueryException: Error preparing query: No tables used
I have tried also with:
sql = "INSERT INTO calendario (year, mes, dia, date) "
+ "SELECT ?,?,?,? "
+ "WHERE NOT EXISTS ("
+ "SELECT * FROM calendario "
+ "WHERE year = ? AND mes = ? AND dia = ?)";
And the error change:
Error preparing query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT * FROM calendario WHERE year = ? AND mes = ? AND dia = ' at line 1
Help me please.
Upvotes: 0
Views: 499
Reputation: 142298
Get rid of both SELECTs
, turn the INSERT
into INSERT IGNORE
:
INSERT IGNORE INTO calendario (year, mes, dia, date)
VALUES
( ?, ?, ?, ? )
will insert a new row if it does not already exist.
And add UNIQUE(year, mes, dia)
so that it knows when to "ignore".
Upvotes: 1