本来打算做一个简单的CRUD操作
但是发现Python对DB的操作还没有介绍,你懂的。
Python可以操作多种数据库,
仅针对sqlite做简单的操作,其他类同
一:下载sqlite,安装
http://www.sqlite.org/download.html
sqlite-shell-win32-x86-3071100.zip
(253.56 KiB)
下载它,然后解压缩,恭喜你,
sqlite搞定了。
解压缩后文件夹下只有一个文件sqlite3.exe,CMD下,cd到这个目录,执行sqlite3.exe test.db
恭喜你,数据库创建成功了。
你可以在cmd中各种命令搞定sqlite,嘿嘿,下面看看python怎么搞定它。
二:python搞定它
官方doc
http://docs.python.org/py3k/library/sqlite3.html
那么,要是使用sqlite3模块了,
To use the module, you must first create a Connection object that represents the database.
用这个模块,你必须首先建立一个链接来表示db
import sqlite3
You can also supply the special name :memory: to create a database in RAM.
你也可以把数据库建立在内存中,
官方doc写的很好,强烈推荐看看,所以下面的例子,都是很简单的,LZ发现实在没法比官方doc写更好,忍了,本来还想直接上官方doc的,但是发现不行。
官方doc是e文,本想翻一下,但是发现几乎不需要翻译,就能看懂。囧!!!
建表,删表,增加,查询写了,那么删除和更新还能不会搞吗?
import sqlite3
#To use the module, you must first create a Connection object that represents the database.
def createTable():
# You can also supply the special name :memory: to create a database in RAM.
# 采用特殊名称:memory:可以建在内存中
conn = sqlite3.connect('sqlite/example')
print(conn,'建立成功')
#cursor必须要有,否则,你啥也干不了
c = conn.cursor()
# 建表
c.execute('create table test (id int, name text)')
# 增加一行
c.execute("insert into test values (1,'jack')")
# 提交
conn.commit()
# 关闭
c.close()
conn.close()
#查询
def find():
conn = sqlite3.connect('sqlite/example')
c = conn.cursor()
c.execute('select * from test')
res = c.fetchall()
for row in res:
print(row)
def dropTable():
conn = sqlite3.connect('sqlite/example')
c = conn.cursor()
c.execute('drop table test')
conn.commit()
c.close()
conn.close()
#要使用绑定变量的方法,不要使用字符串拼接的方式
def findById(id):
conn = sqlite3.connect('sqlite/example')
c = conn.cursor()
c.execute('select * from test where id = ? ',(id,))
print(c.fetchall())
#插入
def insert():
conn = sqlite3.connect('sqlite/example')
c = conn.cursor()
c.execute("insert into test values (2,'tom')")
conn.commit()
c.close()
conn.close()
#批量插入,使用变量绑定
def insertLarge():
conn = sqlite3.connect('sqlite/example')
c = conn.cursor()
for r in [(3, 'lily'),(4, 'cati')]:
c.execute("insert into test values (?,?)",r)
conn.commit()
c.close()
conn.close()
#dropTable()
#createTable()
#insert()
#findById(2)
#insertLarge()
find()