2016-11-30 42 views
0

我正在使用準備好的語句插入白色WHERE NOT EXISTS。我嘗試過不同的方式,但它根本行不通。 我趕上與catch (SQLException sqle)的誤差java.sql.SQLException:準備查詢時出錯:沒有使用表格

java.sql.SQLException: Error preparing query: No tables used

我的代碼是:

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的,它打印此錯誤:

Caused by: org.mariadb.jdbc.internal.util.dao.QueryException: Error preparing query: No tables used

我有也嘗試:

sql = "INSERT INTO calendario (year, mes, dia, date) " 
            + "SELECT ?,?,?,? " 
            + "WHERE NOT EXISTS (" 
            + "SELECT * FROM calendario " 
            + "WHERE year = ? AND mes = ? AND dia = ?)"; 

而錯誤更改:

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

請幫助我。

+0

選擇中沒有from子句。 – NineBerry

+3

您可能想要插入日曆(年,mes,dia,日期)「 +」VALUES(?,?,?,?)「 +」WHERE NOT EXISTS(SELECT * FROM calendario WHERE「 +」year =?AND mes =?AND dia =?)「' – 2016-11-30 19:58:40

+1

您可以在數據模式和字段名稱上使用完整的西班牙語或全英文版,不要混淆它們! – Hackerman

回答

1

擺脫兩個SELECTs的,轉成INSERTINSERT IGNORE:如果它不存在

INSERT IGNORE INTO calendario (year, mes, dia, date) 
    VALUES 
    (?, ?, ?, ?) 

將插入新行。 並添加UNIQUE(year, mes, dia),以便它知道何時「忽略」。