![](/img/trans.png)
[英]How do I import a CSV file into sqlite3 in Python without knowing ahead of time the number of columns?
[英]How can I import a csv file without primary key to sqlite3
我想用存儲在csv文件中的初始數據填充一個新的數據庫。 我試圖使用odo用CSV文件的內容填充現有表。 我的文件沒有主鍵,並且列數不匹配,因為數據庫定義了其他列。
如何使用odo來實現這一目標?
from sqlalchemy import Column, String, Integer, create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Test(Base):
__tablename__ = 'testtable'
uid = Column(Integer, primary_key=True)
colA = Column(String(50))
colB = Column(String(50))
comment = Column(String(100))
engine = create_engine('sqlite:///testdb.db')
Base.metadata.create_all(engine)
我的csvfile看起來像這樣:
col A;col B
aa;bb
ax;bx
這不起作用:
from odo import odo
odo('csvfile.csv',
'sqlite:///testdb.db::testtable',
has_header=True)
錯誤信息:
expected 4 columns but found 3 - filling the rest with NULL
INSERT failed: datatype mismatch
查看您的初始表-您的csv僅帶有兩列,並且正在生成第三列(可能是主鍵)。 檢查是否不需要注釋(或使用下面的示例中的一些默認文本),然后將每個值顯式放入數據庫列中,或考慮在初始填充期間刪除該列,並在初始填充后重新創建。
這是將每個值顯式放置在相應列中的示例。 這解決了sqlite3無法將可用列提供的輸入數量對齊的問題:
import csv
# just my flavor...
with open('csvfile.csv', 'r') as csvfile:
# Next three lines detect dialect
dialect = csv.Sniffer().sniff(csvfile.read(1024))
# csvfile.seek(1,0) skips the first line of the file containing headers
csvfile.seek(1,0)
reader = csv.reader(csvfile, dialect)
for line in reader:
A = line[0]
B = line[1]
rec = Test(colA=A, colB=B,comment='default text')
session.add(rec)
session.commit()
為了避免所有問題,在填充數據庫之前,請不要使用注釋:
class Test(Base):
__tablename__ = 'testtable'
uid = Column(Integer, primary_key=True)
colA = Column(String(50))
colB = Column(String(50))
這應該允許使用您的odo來填充數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.