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