[英]Insert List of tupels in mysql Db using python
I am trying to insert a list of tuples with numbers which I got from a csv file, into my MySQL DB.我正在尝试将从 csv 文件中获得的带有数字的元组列表插入到我的 MySQL 数据库中。
Code I have:我有代码:
readcsv = pd.read_csv( "***********************.csv", skiprows=45, sep=";")
cols = str(readcsv.columns.values.tolist()).replace('[','').replace(']', '').replace('\'','`')
for i in range(0, readcsv.shape[0], 1):
values = str(readcsv.iloc[i:i+1].values.tolist()).replace('[', '(').replace(']', ')').replace('((', '(').replace('))', ')')
print(values)
conn = pymysql.connect(host='****', port=3306, user='root', passwd='*****', db='***')
cursor = conn.cursor()
rows = [values]
a = ','.join(map(str ,rows))
b = ','.join(map(str ,rows))
c =','.join(map(str ,rows))
d =','.join(map(str ,rows))
sql = "INSERT INTO csv_files.csv_file(ms, Power_in_W,Distance_in_mm,Force_in_N) VALUES ({},{},{},{})".format(a,b,c,d)
cursor.execute(sql)
conn.commit()
conn.close()
I already created a db in mySQL with the colums MS, Power_in_W, Distance_in_mm, Force_in_N.我已经在 mySQL 中用列 MS、Power_in_W、Distance_in_mm、Force_in_N 创建了一个数据库。 But somehow I cannot insert the data from the csv into it.
但不知何故,我无法将 csv 中的数据插入其中。 Because of the error:
因为错误:
pymysql.err.InternalError: (1241, 'Operand should contain 1 column(s)')
pymysql.err.InternalError: (1241, '操作数应包含 1 列')
Output I get with print(values)
is:我用
print(values)
得到的输出是:
(1.0, 0.0, 0.0, 0.0), (2.0, 60.3, 960.0, 0.0), (3.0, 60.3, 964.0,0.0), (4.0, 60.3, 967.0, 0.0), (5.0, 61.89, 964.0, 0.0), (6.0, 61.89, 967.0, 0.0), (7.0, 13.69, 962.0, 0.0)
... ...
Does anyone knows what i am doing wrong?有谁知道我做错了什么?
use the execute_many method, and pass values as parameter.使用execute_many方法,并将值作为参数传递。
sql = "INSERT INTO csv_files.csv_file(ms, Power_in_W,Distance_in_mm,Force_in_N) VALUES (%s, %s, %s, %s)"
cursor.executemany(sql, values)
Got it.知道了。 - Problem solved.
- 问题解决了。 only used Parameter a, changed the size of my MS value and last but not least i put everything into the for-loop.
仅使用参数 a,更改了我的 MS 值的大小,最后但并非最不重要的一点是,我将所有内容都放入了 for 循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.