我想将文本文件数据导出到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
答案 0 :(得分:0)
以逗号分隔行,因为必须为该执行字符串提供5个参数。另外,您应该明确命名这些列:
mycursor.execute("INSERT INTO emp_details (Id, Firstname, Lastname, department, salary) VALUES (%s,%s,%s,%s,%s)", x.split(","))
答案 1 :(得分:0)
在您的代码中,您没有提到列以及如何拆分数据
此代码非常好
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")
f.next()
for x in f:
print (x)
sql=("INSERT INTO emp_details (Id,Firstname,Lastname,department, salary) VALUES (%s,%s,%s,%s,%s)")
var=( x.split(","))
mycursor.execute(sql,var)
conn.commit()
print(mycursor.rowcount, "record inserted.")