使用pymysql将csv上传到数据库

3
我正在使用pymysql将csv文件上传到我的数据库中。
我正在使用以下代码:
    #!/usr/bin/python
# -*- coding: utf-8 -*-
import pymysql
import codecs
import csv
import urllib2
import pymysql.cursors

# Get  Data
csvfile = csv.reader(codecs.iterdecode(file('match_urls-2016-03-04', 'utf-8'))

# Connect to the database

connection = pymysql.connect(host='host.com', user='', password='', db='', cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        sql = "INSERT INTO Urlup(URL) VALUES(%s)"
        next(csvfile, None)
        for line in csvfile:
            cursor.execute(sql, (line[0]))

finally:
    connection.commit()
    connection.close()

但是我遇到了“连接”无效语法的错误,不确定该使用什么或者脚本是否能正常工作。

enter image description here

1个回答

3

您需要将查询参数作为元组传递,逗号是不同的关键:

cursor.execute(sql, (line[0], ))
#                       HERE^

同时,你漏掉了右括号:

csvfile = csv.reader(codecs.iterdecode(file('match_urls-2016-03-04', 'utf-8')))
#                                                                         HERE^ 

谢谢 - 在 connection = pymysql.con 上仍然出现无效语法错误。 - emma perkins
@emmaperkins,你能否请发布完整的错误回溯信息?谢谢。 - alecxe
我只得到了在我的主问题中发布的内容。 - emma perkins
@emmaperkins 谢谢您提供的额外信息,已更新答案。希望能对您有所帮助。 - alecxe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接