大多数python(3)风格的从MySQL数据库重复选择的方法

2024-04-26 04:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个客户id的csv文件(CRM_id)。我需要从数据库的customers表中获取它们的主键(autoincrement 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风格的方式(但很高兴听到其他方式)。你知道吗

现在是丑陋的密码。它可以工作,但我讨厌附加到列表中,因为它必须为每个循环复制和重新分配内存,对吗?有没有更好的方法(pre-allocate+enumerate)来跟踪索引,但是有没有更快捷/更好的方法,巧妙地使用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文件中分配一些其他数据(customer id主键是这些其他表的外键,分配算法会发生变化,因此最好能够灵活地用python进行分配,而不是硬编码SQL查询)。我知道这听起来有点倒退,但“客户机”只适用于电子表格,而不是ERP/PLM,所以我必须自己为这个小应用程序建立“关系”。你知道吗


Tags: 文件csvcsvfileinididsforwith
2条回答

如何更改查询以获得所需内容?你知道吗

crm_ids = ",".join(customers)
select_customer = "SELECT UNIQUE id FROM customers WHERE CRM_id IN (%s);" % crm_ids

根据the manual,MySQL甚至可以处理一个多兆字节的查询;如果它是一个真正的长列表,您可以随时将其分解—两个或三个查询保证比几千个查询快得多。你知道吗

将csv存储在dict而不是列表中如何:

customers = [c for c in customerfile]

变成:

customers = {c['CRM_id']:c for c in customerfile}

然后选择整个外部参照:

result = cursor.execute('select id, CRM_id from customers')

并在dict中添加新rowid作为新条目:

for row in result:
    customers[row[1]]['newid']=row[0]

相关问题 更多 >