循环遍历记录并更新 sql table(如果存在)使用 Pyodbc 或 pandas

Loop through records and update sql table if exists using Pyodbc or pandas

我想知道 Python 是否有办法使用 pyodbc 循环遍历 table 的记录,如果它看到一个空白(即 ' ' )字段更改值为空。 我有一个有效的 python 脚本,它将在 table 中列出值。从这里不确定如何遍历行并确定该列是否充满空格以及是否将值更改为 null。它基本上是 ssis 清理的东西,但不想经历使用 ssis 的麻烦。想尝试 python 这是代码

import pyodbc
import time
start_time = time.time()

conn = (
  r'Driver={SQL Server};'
  r'Server=<enter Server here>;'
  r'Database=<enter Database here;'
  r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn)
cursor = cnxn.cursor()

# Create SQL Statement to get rows
sql = """
Select UserOrderField2 From TestAccountPD
where UserOrderField2 = ''
"""
# put all into rows variable
rows = cursor.execute(sql).fetchall()

for row in rows:
  print(row)

cursor.close
cnxn.close()
print("---%s seconds ---" % (time.time() - start_time))

您不需要遍历行。事实上,您应该尽可能避免遍历行,因为它几乎总是 much 比执行单个 UPDATE 操作慢。在你的情况下会是这样的

sql = """\
UPDATE TestAccountPD SET UserOrderField2 = NULL
WHERE LEN(LTRIM(UserOrderField2)) = 0
"""
cursor.execute(sql)
cnxn.commit()