读取csv文件的python和MySQL在字符串格式化过程中并不是所有的参数都被转换。

问题描述 投票:0回答:1

先谢谢你回答我的问题。

我试图创建一个表,读取csv文件,然后将文件中的数据保存到创建的表中。我一直得到这个错误,我不知道如何解决。我看了其他的帖子,但是没有一个能解决我的问题。

csv文件有两列和3000多行。第一列名称是#timestamp,第二列是Vehicle1。下面是我的代码

import csv
import MySQLdb


mydb = MySQLdb.connect(
        host = "localhost",
        user = "root",
        password = "1111",
        database = "LOAD_PROFILES"

)


mycursor = mydb.cursor()

mycursor.execute("DROP TABLE IF EXISTS Household1")



mycursor.execute("SHOW DATABASES;")



for db in mycursor:
    print(db)



sql = " CREATE TABLE Household1(sx TIMESTAMP NOT NULL, Vehicle1 INT NOT NULL, id INT NOT NULL  AUTO_INCREMENT PRIMARY KEY) AUTO_INCREMENT = 1"
mycursor.execute("SHOW TABLES")
mycursor.execute(sql)

fname=input('file name: ')
if len(fname) < 1 : fname="converted0.csv"
with open(fname) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        print(row)
        res = row[0].split()
        TIMESTAMP = row[0]
        Vehicle1 =row[1]
        data = mycursor.execute('''INSERT INTO Household1 VALUES (%s, %s)''',row)
        mycursor.execute("select * from Household1")
        row = mycursor.fetchall()
mycursor.execute("select * from Household1")
f = mycursor.fetchall()
print(f)
mydb.commit()

这是我得到的错误。

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/MySQLdb/cursors.py", line 238, in execute
    query = query % args
TypeError: not all arguments converted during string formatting
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "MySQL_python_Tables.py", line 49, in <module>
    data = mycursor.execute('''INSERT INTO Household1 VALUES (%%s, %%s)''',row)
  File "/usr/lib/python3/dist-packages/MySQLdb/cursors.py", line 240, in execute
    self.errorhandler(self, ProgrammingError, str(m))
  File "/usr/lib/python3/dist-packages/MySQLdb/connections.py", line 52, in defaulterrorhandler
    raise errorclass(errorvalue)
_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting

任何帮助将是感激的,谢谢

EDIT.我的表有三列(最后一列是id列),但我的csv文件只有两列。

原来我的表有三列(最后一列是id列),但我的csv文件只有两列。当我删除了id列之后,就可以正常工作了。

现在我又遇到一个问题,python在我的文件中迭代,直到到 "2010-03-14 02:00:00",然后抛出这个错误。

1292, "Incorrect datetime value: '2010-03-14 02:00:00' for column 'sx' at row 1"

我看了很多帖子,大部分都说这和DST有关。我怎么才能解决这个问题呢?

谅谅

python mysql-python
1个回答
0
投票

在这一行中,你有两个占位符。

mycursor.execute('''INSERT INTO Household1 VALUES (%s, %s)''',row)

你有两个占位符 %s, %s但只有一个论点 row. 占位符的数量应与元组中应结束的参数数量相等。

© www.soinside.com 2019 - 2024. All rights reserved.