python - 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
解决方案
推荐阅读
- python - 为什么我不能 pip 安装 Python3 包?
- python - 使响应成为 `turtle.right()` 中的角度
- reactjs - ReactJS:是否可以动态更改我的“数据目标”属性?而不是单独设置它们?
- javascript - 如何完整获取一周中的某一天?
- r - 列值的字母顺序不正确
- javascript - 有没有办法只循环更新一个纯Javascript的内容?
- c# - XmlSerializer 将 C# 对象转换为 xml 字符串问题
- matlab - 如何使用函数 eraseBetween (Matlab R2019a) 删除多个文件中的字符串
- c++ - 素数实现
- c# - 调用异步方法时是否必须调用等待?