python操作sqlite的CRUD实例分析

yipeiwu_com5年前Python基础

本文实例讲述了python操作sqlite的CRUD实现方法。分享给大家供大家参考。具体如下:

import sqlite3 as db
conn = db.connect('mytest.db')
cursor = conn.cursor()
cursor.execute("drop table if exists datecounts")
cursor.execute("create table datecounts(date text, count int)")
cursor.execute('insert into datecounts values("12/1/2011",35)')
cursor.execute('insert into datecounts values("12/2/2011",42)')
cursor.execute('insert into datecounts values("12/3/2011",38)')
cursor.execute('insert into datecounts values("12/4/2011",41)')
cursor.execute('insert into datecounts values("12/5/2011",40)')
cursor.execute('insert into datecounts values("12/6/2011",28)')
cursor.execute('insert into datecounts values("12/7/2011",45)')
conn.row_factory = db.Row
cursor.execute("select * from datecounts")
rows = cursor.fetchall()
for row in rows:
  print("%s %s" % (row[0], row[1]))
cursor.execute("select avg(count) from datecounts")
row = cursor.fetchone()
print("The average count for the week was %s" % row[0])
cursor.execute("delete from datecounts where count = 40")
cursor.execute("select * from datecounts")
rows = cursor.fetchall()
for row in rows:
  print("%s %s" % (row[0], row[1]))

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Pytorch Tensor基本数学运算详解

1. 加法运算 示例代码: import torch # 这两个Tensor加减乘除会对b自动进行Broadcasting a = torch.rand(3, 4) b = to...

手把手教你pycharm专业版安装破解教程(linux版)

手把手教你pycharm专业版安装破解教程(linux版)

1.首先到jetbrains下载专业版 https://www.jetbrains.com/pycharm/download/#section=linux 我这里下载的是pycharm-...

用 Python 连接 MySQL 的几种方式详解

用 Python 连接 MySQL 的几种方式详解

尽管很多 NoSQL 数据库近几年大放异彩,但是像 MySQL 这样的关系型数据库依然是互联网的主流数据库之一,每个学 Python 的都有必要学好一门数据库,不管你是做数据分析,还是网...

python3多线程知识点总结

多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理。 用户界面可以更加吸引人,比如用户点击了一个按钮去触发某些事件的处理,可以...

使用IDLE的Python shell窗口实例详解

使用IDLE的Python shell窗口实例详解

启动IDLE后会打开Python shell窗口。当键入代码 时,它会基于Python语法提供自动缩进和代码着色功能。 使用IDLE中的Python shell。代码在输入时会自动着...