我正在使用准备好的语句来插入whit WHERE NOT EXISTS。我尝试了不同的方法,但它根本行不通。
我用catch (SQLException sqle)
收到的错误是
java.sql.SQLException:准备查询时出错:没有使用表
我的代码是:
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);
}
我正在使用MariaDB,它会打印此错误:
引起:org.mariadb.jdbc.internal.util.dao.QueryException:准备查询时出错:没有使用表格
我也尝试过:
sql = "INSERT INTO calendario (year, mes, dia, date) "
+ "SELECT ?,?,?,? "
+ "WHERE NOT EXISTS ("
+ "SELECT * FROM calendario "
+ "WHERE year = ? AND mes = ? AND dia = ?)";
错误发生了变化:
准备查询时出错:您的SQL语法中有错误;查看与您的MariaDB服务器版本对应的手册,以便在'WHERE NOT EXISTS附近使用正确的语法(SELECT * FROM calendario WHERE year =?AND mes =?AND dia ='at line 1
请帮帮我。
答案 0 :(得分:1)
摆脱SELECTs
,将INSERT
转为INSERT IGNORE
:
INSERT IGNORE INTO calendario (year, mes, dia, date)
VALUES
( ?, ?, ?, ? )
如果新行尚不存在,将插入新行。
并添加UNIQUE(year, mes, dia)
,以便知道何时"忽略"。