2011-07-01 46 views
1

我嘗試使用python腳本將值插入到我的sqlite表中。爲CSV 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. 

我認爲問題在於這個新的'information'列包含幾行te xt所以我可能會錯誤地將其指定爲'文本'。我的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() 
+0

您可以發佈代碼塊而不是隻創建表的那一行嗎? – 2011-07-01 09:14:55

+0

是的,對不起,我已經添加了完整的腳本。我應該最初發布它,抱歉,謝謝! – medley

+0

請參閱我的答案中的第二個編輯,瞭解使用csv模塊的重新編譯的程序版本。 – 2011-07-03 20:10:16

回答

1

似乎您試圖重新發明輪子有點在這裏:)

嘗試使用Python的CSV模塊;我已經廣泛地使用它,它工作得很好: http://docs.python.org/library/csv.html

它適用於正確形成具有多行文本的csv文件。

編輯:

例如,你可以使用CSV行(這是列表)直接在執行功能:

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() 
+0

哈哈謝謝!我傾向於嘗試重新發明輪子。該文檔很好,但我不確定如何實現它,該模塊的輸出會給我一個sqlite數據庫嗎?感謝您的建議! – medley

+0

我試過並得到'NameError:name'sql'未定義' – medley

+0

是的我的意思是純粹是一個關於csv模塊如何爲每個記錄提供正確解析的例子,因此您不必費心解釋直接自己的CSV文件。我會用你的程序編輯我的帖子(儘管我不保證它會被編譯,甚至更少的工作,因爲我只是試圖把我的例子放在你的上下文中)。 – 2011-07-03 18:10:00

相關問題