我有一个客户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,所以我必须自己为这个小应用程序建立“关系”。你知道吗
如何更改查询以获得所需内容?你知道吗
根据the manual,MySQL甚至可以处理一个多兆字节的查询;如果它是一个真正的长列表,您可以随时将其分解—两个或三个查询保证比几千个查询快得多。你知道吗
将csv存储在dict而不是列表中如何:
变成:
然后选择整个外部参照:
并在dict中添加新rowid作为新条目:
相关问题 更多 >
编程相关推荐