首页 > 解决方案 > mysql trigger not allowing me to retrieve my LAST_INSERT_ID

问题描述

I am trying to retrieve the ID of an inserted row which I need to insert into a row of a different table. but I keep getting 0 prints

I created a table with a trigger which allows auto-increments my VARCHAR primary key, but I think it doesn't allow me to retrieve my last_insert_ID. I have checked the database side (Access: MyPHPAdmin) and I still keep returns of 0. I have also created a similar database without the trigger and set my primary ID as an integer and all the Last_Insert_ID retrieval methods work perfectly.

considering that my prints are 0(zero), I have changed my trigger set values to an empty white space'', instead of NULL. this didn't change anything.

cc_ins_sql = """INSERT into client_contractor(client_contractor, category, address, phone_number) values(%s,%s,%s,%s)"""
cc = raw_input("Client/ Contractor Name: ")
cat = raw_input("Client or Contractor?: ")
cc_addy = raw_input("Client/ Contractor Address: ")
pn = raw_input("Phone Number: ")
cc_ins_val = (cc, cat, cc_addy, pn)
my_cur.execute(cc_ins_sql, cc_ins_val)
my_cur.execute('SELECT LAST_INSERT_ID()')
c_id = my_cur.fetchone()
print c_id
my_db.commit()

my table and trigger creation to (provide more insight)

def c_c():
    cc_seq_table = "CREATE TABLE cc_seq(id INTEGER NOT NULL AUTO_INCREMENT 
    PRIMARY KEY);"
    my_cur.execute(cc_seq_table, my_db)
    try:
        cc_sql = """CREATE TABLE client_contractor(client_contractor_ID     
        VARCHAR(6) NOT NULL PRIMARY KEY, client_contractor text, category 
        text, address text, phone_number text);"""
        my_cur.execute(cc_sql, my_db)
        cc_trigger = """CREATE TRIGGER tg_client_contractor_insert BEFORE 
        INSERT on client_contractor for each row BEGIN INSERT into cc_seq 
        VALUES(NULL); SET NEW.client_contractor_ID =                
        CONCAT('CC', LPAD(LAST_INSERT_ID(), 4, '0')); END"""
        my_cur.execute(cc_trigger)
        my_db.commit()
    except Error as e:
        print e
        return None

image link provided below of output from MyPHPAdmin

标签: pythontriggersinsertmysql-connector-pythonlast-insert-id

解决方案


推荐阅读