python连接sqlite非常简单,基本步骤如下:
- 用sqlite3.connect创建数据库连接,假设连接对象为conn
- 如果该数据库操作不需要返回结果,就直接用conn.execute查询,如建表、删表、添加、修改删除数据等,需要conn.commit()
- 如果需要返回查询结果则用conn.cursor创建游标对象cur, 通过cur.execute查询数据库,用cur.fetchall/cur.fetchone/cur.fetchmany返回查询结果。使用完后,关闭cur
- 关闭conn
以下是基本用法,创建test.db文件,添加一张dept表,添加4条数据,再删除一条,最后读取数据
1.Python SQLITE数据库导入模块:
import sqlite3
2.创建数据库/打开数据库:
conn = sqlite3.connect(“D:/sqlitedata/test.db”)
我们不需要手动的去创建一个sqlite数据库,在调用connect函数的时候,指定库名称,如果指定的数据库存在就直接打开这个数据库,如果不存在就新创建一个再打开。
3.删除表
conn.execute(“drop table dept”)
4.创建表
conn.execute(“create table dept (deptno integer primary key, dname varchar(14), loc varchar(13))”)
5.插入数据。插入数据后,需要commit,才能看到数据
conn.execute(“insert into DEPT (DEPTNO, DNAME, LOC)values (10, ‘ACCOUNTING’, ‘NEW YORK’)”)
conn.execute(“insert into DEPT (DEPTNO, DNAME, LOC)values (20, ‘RESEARCH’, ‘DALLAS’)”)
conn.execute(“insert into DEPT (DEPTNO, DNAME, LOC)values (30, ‘SALES’, ‘CHICAGO’)”)
conn.execute(“insert into DEPT (DEPTNO, DNAME, LOC)values (40, ‘OPERATIONS’, ‘BOSTON’)”)
conn.commit()
6.删除数据。删除数据,也需要commit。
conn.execute(“delete from dept where deptno = ‘10’”)
conn.commit()
7.查询数据
cur = conn.cursor()
cur.execute(“select * from dept”)
#print cur.fetchone()
#print cur.fetchmany()
print cur.fetchall()
cur.close()
8.关闭数据库
conn.close()
完整例子如下:
#coding=utf-8
import sqlite3
conn = sqlite3.connect(“D:/sqlitedata/test.db”)
# 删除表
def dropTable():
conn.execute(“drop table dept”)
conn.commit()
# 创建表
def createTable():
conn.execute(“create table dept (deptno integer primary key, dname varchar(14), loc varchar(13))”)
conn.commit()
# 插入数据
def insertData():
conn.execute(“insert into DEPT (DEPTNO, DNAME, LOC)values (10, ‘ACCOUNTING’, ‘NEW YORK’)”)
conn.execute(“insert into DEPT (DEPTNO, DNAME, LOC)values (20, ‘RESEARCH’, ‘DALLAS’)”)
conn.execute(“insert into DEPT (DEPTNO, DNAME, LOC)values (30, ‘SALES’, ‘CHICAGO’)”)
conn.execute(“insert into DEPT (DEPTNO, DNAME, LOC)values (40, ‘OPERATIONS’, ‘BOSTON’)”)
conn.commit()
# 删除数据
def deleteData():
conn.execute(“delete from dept where deptno = ‘10’”)
conn.commit()
# 查询数据
def findData():
cur = conn.cursor()
cur.execute(“select * from dept”)
# print cur.fetchone()
# print cur.fetchmany()
print cur.fetchall()
cur.close()
dropTable() # 第一次使用该文件时,请注释掉该行,不然会提示该表不存在 sqlite3.OperationalError: no such table: dept
createTable()
insertData()
deleteData()
findData()
conn.close()