Ich muss eine INSERT-Anweisung schreiben, die zuerst überprüft, ob die Daten bereits vorhanden sind. Der aktuelle Code ist innerhalb Python psycopg2 zu einem postgresql db verbinden mit:python psycopg2 bedingte Einfügeanweisungen
sql = """IF NOT EXISTS (SELECT * FROM table \
WHERE col_1 = (%s) AND col_2 = (%s)) \
INSERT INTO table (col1, col2) \
VALUES (%s, %s);"""
data = (col1_data, col2_data, col1_data, col2_data)
try:
CURSOR.execute(sql, data)
DB.commit()
except:
print "Cursor failed INSERT INTO table.\n"
, die nicht funktioniert (und ich habe nicht die Qualität Fehler gemacht Handhabung so erhalte ich keine gute Informationen). Also ging ich in psql und habe gerade versucht:
IF NOT EXISTS (SELECT * FROM t WHERE c1=d1 AND c2=d2)
INSERT INTO t (c1, c2) VALUES (d1,d2);
und ich bekam die folgende Fehlermeldung:
ERROR: syntax error at or near "IF"
LINE 1: IF NOT EXISTS (SELECT * FROM table WHERE c1 = d1...
^
so glaube ich meine Fehler in der SQL ist nicht der Python (obwohl ich falsch sein könnte da) funktioniert dies:
sql = """INSERT INTO t2 (col_0, col_1, col_2) \
VALUES (%s, %s, %s);"""
data = (d1, d2, time.time())
try:
CURSOR.execute(sql, data)
DB.commit()
except:
print "Cursor failed to INSERT INTO t2.\n"
Für Tabelle 1, meine CREATE war:
db=> CREATE TABLE table (
col_0 SERIAL PRIMARY KEY,
col_1 varchar(16),
col_2 smallint
);
NOTICE: CREATE TABLE will create implicit sequence "pm_table_ip_id_seq" for serial column "pm_table.ip_id"
NOTICE: CREATE TABLE/PRIMARY KEY will create implicit index "pm_table_pkey" for table "pm_table"
CREATE TABLE
Ich bin dankbar für jede Hilfe und Anleitung.
Sind Sie sicher, dass diese beiden Spalten den Primärschlüssel nicht zusammensetzen können? –