Python_sqlite3
import sqlite3 #导入模块
conn = sqlite3.connect('example.db') #连接数据库
c = conn.cursor()
#创建表
c.execute('''CREATE TABLE stocks(date text,trans text,symbol text,qty real,price real)''')
#插入一条纪录
c.execute("INSERT INTO stocks VALUES('2016-01-05','BUY','RHAT',100,35.14)")
#提交当前事务,保存数据
conn.commit()
#关闭数据库连接
conn.close() connSe = sqlite3.connect('example.db')
c = connSe.cursor()
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
print(row)
#调用自定义函数
import sqlite3
import hashlib #自定义函数
def md5sum(t):
return hashlib.md5(t).hexdigest() #在内存中创建临时数据库
conn = sqlite3.connect(":memory:")
#创建可在SQL语句中调用的函数
conn.create_function("md5",1,md5sum)
cur = conn.cursor()
#在SQL语句中调用自定义函数
cur.execute("select md5(?)",["中国北京".encode()])
print(cur.fetchone()[0])
#占位符的使用
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE people(name_last,age)")
who='Dong'
age=''
#使用问号作为占位符
cur.execute('insert into people values(?,?)',(who,age))
#使用命名变量作为占位符
cur.execute('select *from people where name_last=:who and age=:age',{'who':who,'age':age})
print(cur.fetchone())
#迭代器生成数据
import sqlite3 #自定义迭代器,按顺序生成小写字母
class IterChars:
def __init__(self):
self.count = ord('a')
def __iter__(self):
return self
def __next__(self):
if self.count > ord('z'):
raise StopIteration
self.count +=1
return (chr(self.count-1))
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("create table characcters(c)")
#创建迭代器对象
theIter = IterChars()
#插入记录,每次插入一个英文小写字母
cur.executemany('insert into characcters(c)values(?)',theIter)
#读取并显示所有记录
cur.execute('select c from characcters')
print(cur.fetchall())
#迭代器生成更简洁的方式
#下面的代码则使用了更为简洁的生成器来产生参数:
import sqlite3
import string #包含yield语句的函数可以用来创建生成器对象
def char_generator():
for c in string.ascii_lowercase:
yield (c,) conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("create table characters(c)")
#使用生成器对象得到参数序列
cur.executemany("insert into characters(c)values(?)",char_generator())
cur.execute('select c from characters')
print(cur.fetchall())
import sqlite3
person=[('Hugo','Boss'),('Calvin','Klein')]
conn=sqlite3.connect(":memory:")
#创建表
conn.execute('create table person(firstname,lastname)')
#插入数据
conn.executemany('insert into person(firstname,lastname) values (?,?)',person)
#显示数据
for row in conn.execute('select firstname,lastname from person'):
print(row)
print('I just deleted',conn.execute('delete from person').rowcount,'rows')
'''用来读取数据
fetchone()
fetchmany(size=cursor,arraysize)
fetchall()
'''
import sqlite3 conn = sqlite3.connect('addressBook.db')
conn.execute('create table addressList(name,sex,phon,QQ,address)')
cur = conn.cursor() #创建游标
cur.execute("insert into addressList(name,sex,phon,QQ,address)values('王小丫','女','13111110010','66735','北京市')")
cur.execute("insert into addressList(name,sex,phon,QQ,address)values('李莉莉','女','11231110010','66755','天津市')")
cur.execute("insert into addressList(name,sex,phon,QQ,address)values('李发莉','女','11235410010','66723','开封市')")
conn.commit() #提交事务,把数据写入数据库 cur.execute('select *from addressList')
li=cur.fetchall() #返回所有查询结果
for line in li:
for item in line:
print(item,end=' ')
print() conn.close()
'''Row对象'''
#假设数据以下面的方式创建并插入数据:
import sqlite3
conn = sqlite3.connect('test.db')
c=conn.cursor()
c.execute("create table stocks(date text,trans text,symbol text,qty real,price real)")
c.execute("insert into stocks values('2016-01-05','BUY','RHAT',100,35.14)")
conn.commit() #使用下面的方式来读取其中的数据:
conn.row_factory = sqlite3.Row
c=conn.cursor()
c.execute('select * from stocks')
r=c.fetchone()
print(type(r))
print(tuple(r))
print(r[2])
print(r.keys())
print(r['qty'])
for field in r:
print(field)
conn.close()
Python_sqlite3的更多相关文章
随机推荐
- Unity 5.X扩展编辑器之打包assetbundle
5.x的assetbundle与4.x以及之前的版本有些不同,不过本质是一样的,只不过5.x打包assetbundle更为简单和人性化了,总体来说只需要三个步骤: 第一步:创建打包资源 //这里是一个 ...
- DBA_基本Bash语法汇总
一.变量 1.变量命名可使用英文字母.数字和下划线,必须以英文字母开头,区分大小写. 2.每个shell都拥有自己的变量定义,彼此互不影响. 3.变量直接以等号赋值,注意等号两边不可留空,若等号右侧有 ...
- Xcode中的调试工具栏简介
如下图所示: 从左至右,第一个按钮用来隐藏调试区域. 第二个按钮向你展示断点是否被全局开启或禁用.如果它不是高亮蓝色,则没有断点会被触发. 第三个按钮暂停或继续程序的执行,你一般点击它继续运行到程序的 ...
- centos 系统时间的同步
1.当你的网站架构涉及到多台服务器的时候,服务器之间的时间必须得同步,这样就涉及到了程序的时间的准确性问题,特别是跟时间相关的操作和系统本身的定时任务. 2.时间同步工具:ntpdate,安装方式:y ...
- Media Player Classic - HC 源代码分析 3:核心类 (CMainFrame)(2)
===================================================== Media Player Classic - HC 源代码分析系列文章列表: Media P ...
- RTMPdump(libRTMP) 源代码分析 7: 建立一个流媒体连接 (NetStream部分 2)
===================================================== RTMPdump(libRTMP) 源代码分析系列文章: RTMPdump 源代码分析 1: ...
- Android特效专辑(三)——自定义不一样的Toast
Android特效专辑(三)--自定义不一样的Toast 大家都知道,Android的控件有时候很难满足我们的需求,所以我们需要自定义View.自定义的方式很多,有继承原生控件也有直接自定义View的 ...
- Unity Web自适应浏览器
unity web的自适应浏览器比我想象中要更简单,但是这里也只有更改最简单的东西实现了自适应.发布web时,在playersetting里面设置分辨率为你在Game窗口自定义的分辨率大小,以保证内容 ...
- IOS中的数据存储方式,特点,使用情况
数据存储的核心都是写文件,主要有四种持久化方式:属性列表(Plist),对象序列化,SQLite数据库,CoreData. 存储Plist: 键值进行存储,不能存储对象.对象需要序列化编码才能写入文件 ...
- ruby抓取web页面
一种方法是Net::HTTP.new方法,返回resp码和实际的data: require 'net/http' h = Net::HTTP.new("www.baidu.com" ...