更新时间:2023-01-12 21:01:48
我按照建议为ID创建了额外的表,从而解决了这个问题。 首先,我使用ID号创建一个附加表,然后使用该表从整个数据库中获取所需的结果,最后再次删除ID表。
我花了一些时间才找到正确的语法,但以下内容使我能够快速了解整个过程:
# Transform my list of ID's to a list of lists
id_list = [[id] for id in ids]
ID_TABLE = 'id_db_name'
conn = pyodbc.connect(driver='{ODBC Driver 17 for SQL Server}',
server='MY_SERVER',
database='MY_DATABASE',
uid='USERNAME', pwd='PASSWORD')
cursor = conn.cursor()
# Create a new table to store the ID's
create_table = "CREATE TABLE id_db_name (Casenr varchar(12));"
cursor.execute(create_table)
cursor.commit()
# Fill the new ID table with my data
insert_to_tmp_tbl_stmt = f"INSERT INTO {ID_TABLE} VALUES (?)"
cursor.fast_executemany = True
cursor.executemany(insert_to_tmp_tbl_stmt, id_list)
# Get the rows from my full database based on the created ID table
compare = f"SELECT * FROM full_db_name WHERE Casenr in (SELECT * FROM id_db_name)"
cursor.execute(compare)
results = cursor.fetchall()
# Delete the ID table
delete_table = "DROP TABLE dbo.tempTable"
cursor.execute(delete_table)
cursor.commit()
# Close the connection
cursor.close()
conn.close()
虽然上面的代码可能可以稍微清理一下(我自己还在努力学习语法,但我对SQL还很陌生),但是即使对于大型的ID表,它也是功能强大、速度快的。