[英]How to insert data list, array into database MySQL using python?
i want to insert it into database, please help me to solve it.我想把它插入数据库,请帮我解决它。
import numpy as np
import sys
import mysql.connector
from mysql.connector import Error
id = 'PEL0005,PEL0006,PEL0007,PEL0008,PEL0009,PEL0010,PEL0011,PEL0012,PEL0013,PEL0014'
p = [[9,1,7,3,14,3,18,2,22,2],[2,2,6,4,4,9,3,3,3,7],[13.9769,12.1656,40.047,28.287,25.1415,47.6875,34.269,38.3822,47.6875,19.575]]
result = ['C2', 'C2', 'C1', 'C2', 'C2', 'C1', 'C3', 'C1', 'C3', 'C2']
def insertData(id, recency, frequency, monetary, result):
try:
connection = mysql.connector.connect(host='localhost', database='myDB', user='root', password='')
cursor = connection.cursor()
query = """INSERT INTO clus_result (id, recency, frequency, monetary, result)
VALUES (%s, %s, %s, %s, %s) """
recordTuple = (id, recency, frequency, monetary, result)
cursor.execute(query, recordTuple)
connection.commit()
print("Inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
insertData(id,p[0],p[1],p[2],result)
Error: Failed to insert into MySQL table Failed processing format-parameters;错误:无法插入 MySQL 表 处理格式参数失败; Python 'list' cannot be converted to a MySQL type
Python 'list' 无法转换为 MySQL 类型
i expect the result: id |我期待结果:id | recency |
新近度 | frequency |
频率 | monetary |
货币 | result
结果
PEL0005 | PEL0005 | 2 |
2 | 13.9789 |
13.9789 | C2
C2
PEL0006 | PEL0006 | 2 |
2 | 12.1656 |
12.1656 | C2
C2
etc.. ETC..
You should do this:-你应该做这个:-
import numpy as np
import sys
import mysql.connector
from mysql.connector import Error
id = 'PEL0005,PEL0006,PEL0007,PEL0008,PEL0009,PEL0010,PEL0011,PEL0012,PEL0013,PEL0014'
p = [[9,1,7,3,14,3,18,2,22,2],[2,2,6,4,4,9,3,3,3,7],[13.9769,12.1656,40.047,28.287,25.1415,47.6875,34.269,38.3822,47.6875,19.575]]
result = ['C2', 'C2', 'C1', 'C2', 'C2', 'C1', 'C3', 'C1', 'C3', 'C2']
def insertData(id, recency, frequency, monetary, result):
try:
connection = mysql.connector.connect(host='localhost', database='myDB', user='root', password='')
cursor = connection.cursor()
query = """INSERT INTO clus_result (id, recency, frequency, monetary, result)
VALUES (%s, %s, %s, %s, %s) """
records = zip(id.split(','), p[0], p[1], p[2], result)
cursor.executemany(query, records)
connection.commit()
print("Inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
insertData(id,p[0],p[1],p[2],result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.