我有一个客户 ID (CRM_id
) 的 csv 文件。我需要从数据库的客户表中获取他们的主键(一个自动增量 int)。 (我不能保证 CRM_id
的完整性,所以我选择不将其作为主键)。
所以:
customers = []
with open("CRM_ids.csv", 'r', newline='') as csvfile:
customerfile = csv.DictReader(csvfile, delimiter = ',', quotechar='"', skipinitialspace=True)
#only one "CRM_id" field per row
customers = [c for c in customerfile]
到目前为止还好吗?我认为这是最符合 Python 风格的方式(但很高兴听到其他情况)。
丑陋的代码来了。它有效,但我讨厌附加到列表,因为它必须为每个循环复制和重新分配内存,对吗?有没有更好的方法(预分配+枚举来跟踪索引浮现在脑海中,但也许有一种更快/更好的方法通过巧妙地使用 SQL 以免执行数千个单独的查询......)?
cnx = mysql.connector.connect(user='me', password=sys.argv[1], host="localhost", database="mydb")
cursor = cnx.cursor()
select_customer = ("SELECT id FROM customers WHERE CRM_id = %(CRM_id)s LIMIT 1;")
c_ids = []
for row in customers:
cursor.execute(select_customer, row)
#note fetchone() returns a tuple, but the SELECTed set
#only has a single column so we need to get this column with the [0]
c_ids.extend(cursor.fetchall())
c_ids = [c[0] for c in c_ids]
编辑: 目的是获取列表中的主键,以便我可以使用这些从链接表中的其他 CSV 文件分配一些其他数据(客户 ID 主键是这些其他表的外键,并且分配算法发生变化,所以它是最好能够灵活地在 python 中进行分配,而不是硬编码 SQL 查询)。我知道这听起来有点落后,但“客户端”只使用电子表格而不是 ERP/PLM,所以我必须自己为这个小应用程序构建“关系”。
最佳答案
如何更改您的查询以获得您想要的内容?
crm_ids = ",".join(customers)
select_customer = "SELECT UNIQUE id FROM customers WHERE CRM_id IN (%s);" % crm_ids
根据 the manual,即使是数兆字节的查询,MySQL 也应该没问题。 ;如果它变得真的很长的列表,您总是可以将它分解 - 两三个查询保证比几千个查询快得多。
关于python - 从 MySQL 数据库中重复选择的大多数 python(3)esque 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802931/