我想将文本文件数据导出到MySQL数据库

import MySQLdb
import re

conn = MySQLdb.connect (host = "127.0.0.1", user = "root", passwd = "123456")
mycursor =conn.cursor()
mycursor.execute("CREATE DATABASE IF NOT EXISTS  EMP")
mycursor.execute("USE  EMP")
mycursor.execute("CREATE TABLE IF NOT EXISTS emp_details  (Id VARCHAR(255) , Firstname VARCHAR(255),Lastname VARCHAR(255),department VARCHAR(255),salary VARCHAR(255)) ")

f = open("new.txt", "rb")
print (f.next())

for x in f:

  mycursor.execute("INSERT INTO emp_details VALUES (%s,%s,%s,%s,%s)",x)
  conn.commit()

print(mycursor.rowcount, "record inserted.")


我收到一个错误

query = query % args
TypeError: not all arguments converted during string formatting


this is what my text file data looks like

最佳答案

在逗号上分割行,因为您必须为该执行字符串提供5个参数。另外,您应该显式命名这些列:

mycursor.execute("INSERT INTO emp_details (Id, Firstname, Lastname, department, salary) VALUES (%s,%s,%s,%s,%s)", x.split(","))

关于python - 如何将文本文件数据导出到mysql数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57120810/

10-11 20:38