pythonmysql游标中的错误消息:“字段列表”中的1054未知列“x”

2024-04-24 19:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的第一个帖子!我也刚开始编程,所以请容忍我!

我试图将一堆.csv文件加载到数据库中,以便以后对数据执行各种报告。首先,我在mysql中创建了几个表,这些表的字段名和数据类型与将加载到表中的内容匹配。我正在操作文件名(以便解析出要用作表中字段的日期),并使用python清理数据。

所以我现在的问题(哈哈…)是,当我尝试对mysql进行“Insert-Into”查询时,收到了这个错误消息。

Traceback (most recent call last):  
File "C:\Program Files\Python\load_domains2.py", line 80, in <module>  
cur.execute(sql)
File "C:\Program Files\Python\lib\site-packages\MySQLdb\cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "C:\Program Files\Python\lib\site-packages\MySQLdb\connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'a1200e.com' in 'field list'")

“a1200e.com”指的是我要插入到该列中的特定域名。我的问题如下:

sql="""INSERT INTO temporary_load
    (domain_name, session_count, search_count, click_count,
    revenue, revenue_per_min, cost_per_click, traffic_date)
    VALUES (%s, %d, %d, %d, %d, %d, %d, %s)""" %(cell[0],
                                                int(cell[1]),
                                                int(cell[2].replace (",","")),
                                                int(cell[3].replace(",","")),
                                                float(cell[4].replace("$","")),
                                                float(cell[5].replace("$","")),
                                                float(cell[6].replace("$","")),
                                                parsed_date)

    cur.execute(sql)

我对这一切都很陌生,所以我确信我的代码一点也不高效,但我只是想把所有的东西都安排好,这样我就清楚了。我不明白的是,我已经确保表中正确定义了数据类型(与查询中的数据类型相对应)。我有什么遗漏吗?我已经试着解决这个问题有一段时间了,不知道会出什么问题

非常感谢!!! 瓦尔


Tags: 数据inpyexecutesqlcountlinecell
2条回答

您应该使用DB-API引用,而不是直接将数据包含在SQL查询中:

sql = """INSERT INTO temporary_load
    (domain_name, session_count, search_count, click_count,
    revenue, revenue_per_min, cost_per_click, traffic_date)
    VALUES (%s, %d, %d, %d, %d, %d, %d, %s)"""
args = (cell[0],
        int(cell[1]),
        int(cell[2].replace (",","")),
        int(cell[3].replace(",","")),
        float(cell[4].replace("$","")),
        float(cell[5].replace("$","")),
        float(cell[6].replace("$","")),
        parsed_date)
cur.execute(sql, args)

这使得DB-API模块正确地引用了这些值,并解决了手工操作时可能遇到的大量问题(通常是错误的)

Thomas和往常一样,是绝对正确的:可以让MySQLdb处理引用问题。

除该建议外:

  1. csv module是您的朋友。
  2. MySQLdb使用PEP 249中详细描述的“format”参数样式。
    这对你意味着什么?
    所有参数,不管是什么type,都应该作为字符串传递给MySQLdb(就像这样的%s)。MySQLdb将确保值正确转换为SQL文本。
    顺便说一下,MySQLdb有一些good documentation
  3. 请随意提供有关源数据的更多详细信息。这可能使诊断问题更容易。

以下是从.csv文件向MySQL数据库插入值的一种方法:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import MySQLdb
import os

def main():
    db = MySQLdb.connect(db="mydb",passwd="mypasswd",) # connection string

    filename = 'data.csv'
    f = open(filename, "rb") # open your csv file
    reader = csv.reader(f)
    # assuming the first line of your csv file has column names
    col_names = reader.next() # first line of .csv file
    reader = csv.DictReader(f, col_names) # apply column names to row values

    to_db = [] # this list holds values you will insert to db
    for row in reader: # loop over remaining lines in .csv file
        to_db.append((row['col1'],row['col2']))
    # or if you prefer one-liners
    #to_db = [(row['col1'],row['col2']) for row in reader]
    f.close() # we're done with the file now

    cursor = db.cursor()
    cursor.executemany('''INSERT INTO mytable (col1,col2) 
                    VALUES (%s, %s)''', to_db) # note the two arguments
    cursor.close()
    db.close()

if __name__ == "__main__":
    main()

相关问题 更多 >