Python-mysql游标错误消息:1054 未知列“x”在'field list'中
这是我第一次发帖!我也刚开始学习编程,所以请多多包涵!
我正在尝试把一堆 .csv 文件导入到数据库中,以便后面可以对这些数据进行各种报告。我首先在 mysql 中创建了一些表,确保字段名称和数据类型与将要导入的内容相匹配。我正在处理文件名(为了提取出日期,以便用作表中的一个字段),并用 python 清理数据。
所以我现在遇到的问题(哈哈……)是,当我尝试执行 '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)
我对这一切都很陌生,所以我知道我的代码肯定不够高效,但我只是想把所有内容都摆出来,让自己更清楚。我不明白的是,我已经确保我的表格定义了正确的数据类型(与我的查询相对应)。我是不是漏掉了什么?我已经尝试解决这个问题一段时间了,但不知道哪里出了错 :/
非常感谢!!!
Val
2 个回答
1
你应该使用数据库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)
这样做可以让数据库API模块自动为你处理数据的格式,避免了很多你手动操作时可能出现的问题(而且通常会出错)。
2
Thomas 说得没错:可以放心让 MySQLdb 来处理引号的问题。
除了这个建议,还有几点:
- csv模块 是你的好帮手。
- MySQLdb 使用的是“格式”参数风格,具体可以参考 PEP 249。
这对你意味着什么呢?
所有的参数,不管是什么类型,都应该以字符串的形式传给 MySQLdb(像这样%s
)。MySQLdb 会确保这些值被正确转换成 SQL 字面量。
顺便提一下,MySQLdb 有一些很好的文档。 - 可以多提供一些关于你的源数据的细节,这样可能会更容易找到问题所在。
下面是一种从 .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()