【发布时间】:2020-09-12 09:26:36
【问题描述】:
我正在使用 python 从文件中插入 maria db 表中的记录。输入文件有标题。某些列完全或部分为空。我正在尝试下面的代码 -
表定义 -
CREATE TABLE `local_db`.`table_x` (
`Unique_code` varchar(50) NOT NULL,
`city` varchar(200) DEFAULT NULL,
`state` varchar(50) DEFAULT NULL,
`population` bigint(20) DEFAULT NULL,
`Govt` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
input_file = "C:\\Users\\input_file.csv"
csv_data = csv.reader(open(input_file))
try:
connection = mysql.connector.connect(host='localhost',
database='local_db',
user='root',
password='root',
port = '3306')
cursor = connection.cursor()
for row in csv_data:
sql = """
INSERT INTO table_x(Unique_code,city,state,population,Govt) \
VALUES(?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE city = VALUES(city),state = VALUES(state), \
population = VALUES(population),Govt = VALUES(Govt)"""
cursor.execute(sql, row)
connection.commit()
print(cursor.rowcount, "Record inserted successfully into table_x")
cursor.close()
except mysql.connector.Error as error:
print("Failed to insert record into table_x table {}".format(error))
finally:
if (connection.is_connected()):
connection.close()
print("MySQL connection is closed")
但我遇到了错误 -
Failed to insert record into table_x table Not all parameters were used in the SQL statement
MySQL connection is closed
请建议我可以在这里做哪些代码更改来处理这种情况。
【问题讨论】:
标签: mysql python-3.x mariadb insert-update