如何确保空表中填充有 psycopg?
我正在尝试找到一种有效而可靠的方法,以确保我的插入
确实已经为我的空表进行了。
While I would like to use a function like this
connection_info = "..."
def insert(statement: str, validate: bool):
with psycopg.connect(connection_info) as connection:
with connection.cursor() as cursor:
cursor.execute(statement)
if validate and not cursor.rowcount > 0:
raise Error("It's not populated")
connection.commit()
I don't know if there's a case where the cursor.rowcount
is over zero, but not committed to the database. So, for now I use the following:
connection_info = "..."
def execute(statement: str):
with psycopg.connect(connection_info) as connection:
with connection.cursor() as cursor:
cursor.execute(statement)
connection.commit()
def is_populated(table: str) -> bool:
with psycopg.connect(connection_info) as connection:
with connection.cursor() as cursor:
cursor.execute(f'SELECT 1 FROM {table}')
rows = cursor.rowcount
connection.commit()
return rows > 0
def insert(statement: str, table: str, validate: bool):
execute(statement)
if validate and not is_populated(table):
raise Error("it's not populated")
What's the best practice to ensure that my data are inserted into my tables?
ps我不知道它是否有和不同,但是我正在使用psycopg3
I am trying to find an efficient and reliable way to ensure that my INSERT
s have indeed taken place for my empty tables.
While I would like to use a function like this
connection_info = "..."
def insert(statement: str, validate: bool):
with psycopg.connect(connection_info) as connection:
with connection.cursor() as cursor:
cursor.execute(statement)
if validate and not cursor.rowcount > 0:
raise Error("It's not populated")
connection.commit()
I don't know if there's a case where the cursor.rowcount
is over zero, but not committed to the database. So, for now I use the following:
connection_info = "..."
def execute(statement: str):
with psycopg.connect(connection_info) as connection:
with connection.cursor() as cursor:
cursor.execute(statement)
connection.commit()
def is_populated(table: str) -> bool:
with psycopg.connect(connection_info) as connection:
with connection.cursor() as cursor:
cursor.execute(f'SELECT 1 FROM {table}')
rows = cursor.rowcount
connection.commit()
return rows > 0
def insert(statement: str, table: str, validate: bool):
execute(statement)
if validate and not is_populated(table):
raise Error("it's not populated")
What's the best practice to ensure that my data are inserted into my tables?
PS I don't know if it makes and difference, but I'm using psycopg3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论