您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python / postgres / psycopg2:获取刚刚插入的行的ID

Python / postgres / psycopg2:获取刚刚插入的行的ID

cursor.execute("INSERT INTO .... RETURNING id")
id_of_new_row = cursor.fetchone()[0]

并且,请不要手动构建包含值的sql字符串。您可以(并且应该!)单独传递值,从而不必进行转义和sql注入:

sql_string = "INSERT INTO domes_hundred (name,name_slug,status) VALUES (%s,%s,%s) RETURNING id;"
cursor.execute(sql_string, (hundred_name, hundred_slug, status))
hundred = cursor.fetchone()[0]

有关更多详细信息,请参见psycopg文档:http ://initd.org/psycopg/docs/usage.html#passing- parameters-to-sql-queries

python 2022/1/1 18:36:05 有336人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶