python插入记录后取得主键id的方法(cursor.lastrowid和conn.insert_id())

本文介绍了一个使用 Python 的 MySQLdb 库连接 MySQL 数据库并插入数据的例子。演示了如何获取用户输入的数据,并通过 SQL 语句将其插入到指定的数据库表中。此外,还展示了如何获取最后一次插入数据的 ID。

http://blog.youkuaiyun.com/xqy1522/article/details/6108883

 

#!/usr/bin/python
# import MySQL module
import MySQLdb
# get user input
name = raw_input("Please enter a name: ")
# connect
conn = MySQLdb.connect(host="localhost", user="nobody", passwd="nobody", conn="qestar", unix_socket="/tmp/mysql.sock")
# create a cursor
cursor = conn.cursor()
# execute SQL statement
cursor.execute("INSERT INTO test (nama) VALUES (%s)", name)
# get ID of last inserted record
print "ID of last record is ", int(cursor.lastrowid) #最后插入行的主键ID
print "ID of inserted record is ", int(conn.insert_id()) #最新插入行的主键ID,conn.insert_id()一定要在conn.commit()之前,否则会返回0
conn.commit()


 

with POOL_D.connection() as conn: with conn.cursor() as cursor: # 获取提取的病名(来自你前面提取的变量) disease_name = extracted_content.get('病名', '').strip() if not disease_name: show_toast("病名为空,无法操作") return # 先查询病名是否存在 select_sql = "SELECT COUNT(*) AS `count` FROM 疾病库 WHERE 病名 = %s" cursor.execute(select_sql, (disease_name,)) result = cursor.fetchone() exists = result['count'] > 0 if result else False if exists: # 如果存在,执行 UPDATE update_sql = """ UPDATE 疾病库 SET 概述 = %s, 特征症状 = %s,详细信息 = %s,链接 = %s,临床表现 = %s WHERE 病名 = %s """ cursor.execute(update_sql, (outline,characteristic_symptoms,html, links_json,clinical_manifestation,self.disease_name)) if cursor.rowcount == 0: show_toast("未找到匹配的病名,可能已被删除") else: conn.commit() show_toast("内容链接已成功更新到数据库,") disease_id = cursor.lastrowid # 将刚刚插入数据库的记录的自增主键 ID 赋值给变量 disease_id。 # 生成向量 symptom_vector = model.encode([characteristic_symptoms], normalize_embeddings=True).astype( "float32") description_vector = model.encode([clinical_manifestation], normalize_embeddings=True).astype( "float32") symptom_index.add(symptom_vector) description_index.add(description_vector) symptom_idx = symptom_index.ntotal - 1 description_idx = description_index.ntotal - 1 symptom_idx_to_id[symptom_idx] = disease_id description_idx_to_id[description_idx] = disease_id # 保存 FAISS 索引映射表 faiss.write_index(symptom_index, SYMPTOM_INDEX_PATH) faiss.write_index(description_index, DESCRIPTION_INDEX_PATH) np.save(SYMPTOM_MAP_PATH, symptom_idx_to_id) np.save(DESCRIPTION_MAP_PATH, description_idx_to_id) show_toast("特征症状临床表现已加入向量库") 这样有问题吗
08-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值