要防止通过pyodbc在SQL Server中插入多条记录,可以采取以下方法:
示例代码:
import pyodbc
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=<server_name>;DATABASE=<database_name>;UID=<username>;PWD=<password>')
cursor = conn.cursor()
# 使用参数化查询插入多条记录
records = [('John', 25), ('Jane', 30), ('David', 35)]
query = 'INSERT INTO <table_name> (name, age) VALUES (?, ?)'
for record in records:
cursor.execute(query, record)
conn.commit()
conn.commit()
提交事务或conn.rollback()
回滚事务。示例代码:
import pyodbc
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=<server_name>;DATABASE=<database_name>;UID=<username>;PWD=<password>')
cursor = conn.cursor()
# 开始事务
conn.autocommit = False
try:
# 插入多条记录
records = [('John', 25), ('Jane', 30), ('David', 35)]
query = 'INSERT INTO <table_name> (name, age) VALUES (?, ?)'
for record in records:
cursor.execute(query, record)
# 提交事务
conn.commit()
except:
# 回滚事务
conn.rollback()
# 恢复自动提交模式
conn.autocommit = True
通过以上方法,可以有效地防止通过pyodbc在SQL Server中插入多条记录。
领取专属 10元无门槛券
手把手带您无忧上云