【发布时间】:2017-03-30 05:41:40
【问题描述】:
我正在尝试编写一个 python 脚本,该脚本将加载我使用 SQL 在 pyhton 中创建的表,并使用来自文本文件的数据自动填充它们。我被困在基本编码上。我确实有一个大致的想法,但是当我尝试运行这种方法时出现错误。我创建了 2 个表。我已阅读文件。该文件是一个逗号分隔的文本文件,没有标题。
文件的前 3 行如下所示。
+ ---- + ----- + -------------------- + -------- + - + --- + ----- +
| John | Smith | 111 N. Wabash Avenue | plumber | 5 | 1.0 | 200 |
| John | Smith | 111 N. Wabash Avenue | bouncer | 5 | 1.0 | 200 |
| Jane | Doe | 243 S. Wabash Avenue | waitress | 1 | 5.0 | 10000 |
+ ---- + ----- + -------------------- + -------- + - + --- + ----- +
import sqlite3
conn= sqlite3.connect('csc455.db')
c = conn.cursor()
#Reading the data file
fd = open ('C:/Users/nasia/Documents/data_hw2.txt','r')
data = fd.readlines()
#Creating Tables
>>> L = """create table L
... (first text, last text, address text, job text, LNum integer,
... constraint L_pk
... primary key(first, last, address, job),
... constraint L_fk
... foreign key (LNum) references LN(LNum)
... );"""
>>> c.execute(L)
LN = """create table LN
... (
... LNum integer, Interest float, Amount, Integer,
... constraint LN_pk
... primary key (LNum)
... );"""
c.execute(LN)
#Inserting into database
for elt in data:
... currentRow = elt.split(", ")[:-1]
... insert = """(insert into LN values (%s, %s, %s);, %(currentRow[4], currentRow[5], currentRow[6]))"""
... c.execute(insert)
这里有一些语法错误。代码停止工作。我无法弄清楚我做错了什么。 错误是 回溯(最近一次通话最后): 文件“”,第 4 行,在 OperationalError:靠近“(”:语法错误
我不知道我做错了什么
【问题讨论】:
-
data_hw2.txt是什么样的?你的数据库架构是什么?你想如何从一个映射到另一个? -
在未来,知道哪个语句引发了错误而不是让我们猜测真的很有帮助!
-
附带说明,您不必将
;放在传递给execute的各个SQL 语句上;仅当您使用命令行工具或执行 SQL 脚本时才需要。