Python3自带了SQLite3数据库,使用前引入即可。
import sqlite3
con = sqlite3.connect('d:/test.db3') #test.db3存在则直接读取,不存在则创建
cur=con.cursor() #游标,可以认为类似于recordset
cur.execute('CREATE TABLE Student(Stuid TEXT, Age INTERGER, Name TEXT)')
cur.execute('INSERT INTO Student VALUES("00001", 20, "Lucy")')
cur.execute('INSERT INTO Student VALUES("00002", 21, "Lily")')
con.commit()
cur.execute('SELECT * FROM Student')
con.text_factory = str #sqlite默认为unicode输出,此处指定为str,即python默认的utf-8
print(cur.fetchone())
print(cur.fetchall())
cur.close()
con.close()
下面是展现Python轻盈、简洁的时候了,可以用下述方式插入数据:
mylist = [("00003", 20, "David"), ("00004", 21, "Richard"),
("00005", 22, "qxzy")]
for s in mylist:
cur.execute('INSERT INTO Student VALUES(?, ?, ?)', (s[0], s[1], s[2]))
con.commit()
最后说明一下SQLite和Python的数据类型对应关系:
SQLite | Python | 说明 |
---|---|---|
NULL | NontType | 啥也不知道 |
INTEGER | int或long | 整数 |
REAL | float | 8字节浮点数 |
TEXT | unicode或str | 字符串 |
BLOB | buffer | 二进制数据(Binary Large OBject) |