欢迎投稿

今日深度:

python使用sqlite简单介绍,pythonsqlite

python使用sqlite简单介绍,pythonsqlite


python连接sqlite非常简单,基本步骤如下:

以下是基本用法,创建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()

www.htsjk.Com true http://www.htsjk.com/SQLite/26116.html NewsArticle python使用sqlite简单介绍,pythonsqlite python连接sqlite非常简单,基本步骤如下: 以下是基本用法,创建test.db文件,添加一张dept表,添加4条数据,再删除一条,最后读取数据 1.Python SQLITE数...
相关文章
    暂无相关文章
评论暂时关闭