[英]Inserting rows of varying lengths into SQLite3 Database with Python
[英]Python sqlite3 database with varying number of columns?
当使用python sqlite3模块时,如果我要创建一个表并且第一行说4列,那么下一行必须要有4列还是我可以多/少?
我正在寻找一个词汇数据库。 每个词可能具有不同数量的定义。
例如,“ set”比“ panacea”有更多的定义。
我将使用一个刮板来处理此词汇数据库,该刮板可以轻松地从字典参考站点中查找单词和定义。
#! /usr/bin/env python
import mechanize
from BeautifulSoup import BeautifulSoup
import sys
import sqlite3
def dictionary(word):
br = mechanize.Browser()
response = br.open('http://www.dictionary.reference.com')
br.select_form(nr=0)
br.form['q'] = word
br.submit()
definition = BeautifulSoup(br.response().read())
trans = definition.findAll('td',{'class':'td3n2'})
fin = [i.text for i in trans]
query = {}
for i in fin:
query[fin.index(i)] = i
## The code above is given a word to look up and creates a 'dict' of its definiton from the site.
connection = sqlite3.connect('vocab.db')
with connection:
spot = connection.cursor()
## This is where my uncertainty is. I'm not sure if I should iterate over the dict values and 'INSERT' for each definition or if there is a way to put them in all at once?
spot.execute("CREATE TABLE Words(Name TEXT, Definition TEXT)")
spot.execute("INSERT INTO Words VALUES(word, Definition (for each number of definitions))")
return query
print dictionary(sys.argv[1])
这不是一项任务,而是更多用于学习sqlite3的个人练习。
您的设计违背了关系数据库的精神( Wikipedia将关系定义为“一组具有相同属性的元组”),而sqlite是其中之一。
此处合适的设计是通过外键链接的单词表和定义表。 如果您的单词除了其内容之外没有其他属性,则可以跳过单词表,而仅使用定义表中的键即可。
但是请注意,每个定义只有一行,而不是每个单词一行。
如果我要创建一个表,并且第一行有4列,那么下一行必须有4列,还是我可以增加/减少?
您无法在SQLite中创建行所在单元格数量不同的表。 不过,您可以将Null
放入行的单元格中。
Perpahs你需要一个1-to-n
关系:每个字可以有很多定义。
编辑:
看一下这张图,其中有两个表Word
和Definiton
:
+------------+
+-------+ | Definition |
| Word | +------------+
+-------+ | id PK |
| id PK |-1---*-| word_id FK |
| text | | text |
+-------+ +------------+
在两个表中, PK
是表的主键 。 FK
标记为一个外键 ,该列是引用其他表的PK的列。 在此图中, Definiton
的FK word_id
引用了Word
的PK id
。 此关系由两行之间的-1---*-
连接表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.