emma perkins
emma perkins

Reputation: 769

Using pymysql to upload csv to database

I am using pymysql to upload a csv file into my database.

I am using the following code:

    #!/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()

but I am getting the error "connection" invalid syntax and unsure what I am supposed to use or even if the script will work

enter image description here

Upvotes: 3

Views: 2171

Answers (1)

alecxe
alecxe

Reputation: 473873

You need to pass the query parameters as a tuple, the comma makes the difference:

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

And, you are missing the closing parenthesis:

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

Upvotes: 3

Related Questions