Указано неверное количество привязок для скрипта CSV Sqlite Python - PullRequest
1 голос
/ 01 июля 2011

Я пытаюсь вставить значения в мою таблицу sqlite, используя скрипт на python.

Это работало отлично, пока я не попытался добавить еще один столбец под названием «информация» - он затем выдал следующую ошибку:

You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings

Итак, я добавил:

conn.text_factory = str

Тогда я получил эту ошибку:

Incorrect number of bindings supplied. The current statement uses 7, and there are 3 supplied.

Мне кажется, проблема в том, что в этом новом столбце «информация» содержится несколько строк текста, поэтому я могу неправильно указать его как «текст». Код моего скрипта Python:

import sqlite3;
from datetime import datetime, date;
import time
conn = sqlite3.connect('mynewtable.sqlite3')
conn.text_factory = str
c = conn.cursor()
c.execute('drop table if exists mynewtable')
c.execute('create table mynewtable(id integer primary key autoincrement, rank integer, placename text, information text, nooftimes integer, visit text, fav integer, year integer)')

def mysplit (string):
quote = False
retval = []
current = ""
for char in string:
    if char == '"':
        quote = not quote
    elif char == ',' and not quote:
        retval.append(current)
        current = ""
    else:
        current += char
retval.append(current)
return retval

# Read lines from file, skipping first line
data = open("mynewtable.csv", "r").readlines()[1:]
for entry in data:
# Parse values
vals = mysplit(entry.strip())

# Insert the row!
print "Inserting %s..." % (vals[0])
sql = "insert into mynewtable values(NULL, ?, ?, ?, ?, ?, ?, ?)"
c.execute(sql, vals)

# Done!
conn.commit()

1 Ответ

1 голос
/ 01 июля 2011

Кажется, вы пытаетесь немного изобретать колесо здесь:)

Попробуйте использовать CSV-модуль Python; Я использовал это широко, и это работает очень хорошо: http://docs.python.org/library/csv.html

Прекрасно работает с правильно сформированными CSV-файлами с многострочным текстом.

EDIT:

Например, вы можете использовать строки csv (которые являются списками) непосредственно в вашей функции execute:

import csv
for row in csv.reader(open('allnamesallyearsn.csv')):
    c.execute(sql, row)

2-е РЕДАКТИРОВАНИЕ:

Согласно моему последнему комментарию, вот код, который вы разместили с использованием модуля csv:

import sqlite3, csv, time
from datetime import datetime, date

conn = sqlite3.connect('mynewtable.sqlite3')
conn.text_factory = str
c = conn.cursor()
c.execute('drop table if exists mynewtable')
c.execute('create table mynewtable('
          'id integer primary key autoincrement, '
          'rank integer, '
          'placename text, '
          'information text, '
          'nooftimes integer, '
          'visit text, '
          'fav integer, '
          'year integer)')

sql_insert = "insert into mynewtable values(NULL, ?, ?, ?, ?, ?, ?, ?)"
csv_reader = csv.reader(open('mynewtable.csv', 'rb'))
csv_reader.next() # skip headers
for csv_row in csv_reader:
    print "Inserting %s..." % (csv_row)
    c.execute(sql_insert, csv_row)

conn.commit()
...