Python sqlite3库

这篇博客介绍了如何使用Python的SQLite3模块进行数据库的基本操作,包括连接数据库、创建游标、创建与删除表、插入与更新数据、执行SELECT查询以及获取数据行数。还展示了如何批量插入数据,并提供了获取数据库表名的方法。
摘要由CSDN通过智能技术生成

SQLite3

连接数据库

//sqlite3是python的嵌入式数据库,只需要导入即可
import sqlite3

conn = sqlite3.connect('dbname.db')//连接数据库,如果没有则创建

创建游标

cursor = conn.cursor()

游标的作用

cursor.execute('SQL commands')
//创建表
cursor.execute('CREATE TABLE tablename')\
cursor.execute('CREATE TABLE tablename(attributes type)')
//插入数据
cursor.execute('INSERT INTO tablename values(attribute`s value)')
//更新表
cursor.execute('UPDATE tablename SET attribute = value')
//select语句配合fetchall()方法获取数据
cursor.execute('SELECT * from tablename')//*指全部,可换成attribute,获得其对应的值
data = cursor.fetchall()
//也可用where语句进行筛选
cursor.execute('SELECT name from tablename WHERE age > 20')
data = cursor.fetchall()//这里获得的就是数据库中table表中年龄大于20的所有人名
//计算行数
cursor.execute('SELECT * from tablename').rowcount
data = cursor.fetchall()
print(len (data))//即打印出全部数据的行数
//同时可以计算删除多少行
cursor.execute('DELIETE from tablename').rowcount
//列出表名
cursor.execute('SELECT name from sqlite_master where type = "table"')
print(cursor.fetchall)
//删除表
cursor.execute('DROP table tablename')
//建立和删除表时,应判断其是否存在
cursor.execute('CREATE table if not exists tablename')
cursor.execute('DROP table if exists tablename')
//插入多行
cursor.execute('CREATE table if not exists projects(id integer, name text)')
data = [(1, "Ridesharing"), (2, "Water Purifying"), (3, "Forensics"), (4, "Botany")] 
cursor.executemany("INSERT INTO projects VALUES(?, ?)", data) //以'?'做占位符
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值