前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python使用sqlite简单介绍

python使用sqlite简单介绍

作者头像
py3study
发布2020-01-07 11:34:18
5670
发布2020-01-07 11:34:18
举报
文章被收录于专栏:python3

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

  1. 用sqlite3.connect创建数据库连接,假设连接对象为conn
  2. 如果该数据库操作不需要返回结果,就直接用conn.execute查询,如建表、删表、添加、修改删除数据等,需要conn.commit()
  3. 如果需要返回查询结果则用conn.cursor创建游标对象cur, 通过cur.execute查询数据库,用cur.fetchall/cur.fetchone/cur.fetchmany返回查询结果。使用完后,关闭cur
  4. 关闭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()

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档