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的更多相关文章
随机推荐
- SpriteBuilder改变布局后App运行出错代码排查
原来整个关卡场景放在GameScene.ccb中,后来觉得移到专门的Level.ccb比较好. 移动过后编译运行,只要移动Player的胳膊发射子弹时,Xcode报错: g due to Chipmu ...
- 网站开发进阶(二十八)初探localStorage
初探localStorage 注: localStorage经典项目应用案例 HTML5中提供了localStorage对象可以将数据长期保存在客户端,直到人为清除. localStora ...
- Leetcode_171_Excel Sheet Column Number
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42290079 Given a column title a ...
- 软考论文的六大应对策略V1.0
软考论文的六大应对策略V1.0 短短2个小时,要写3000字的文章,对习惯了用电脑敲字.办公的IT从业人员而言,难度不小.尤其,大家会提笔忘字.笔者的应试策略,就是勤学苦练,考试前的一个星期,摸清套路 ...
- Retinex图像增强算法
前一段时间研究了一下图像增强算法,发现Retinex理论在彩色图像增强.图像去雾.彩色图像恢复方面拥有很好的效果,下面介绍一下我对该算法的理解. Retinex理论 Retinex理论始于Land和M ...
- iOS开发讲解SDWebImage,你真的会用吗?
SDWebImage作为目前最受欢迎的图片下载第三方框架,使用率很高.但是你真的会用吗?本文接下来将通过例子分析如何合理使用SDWebImage. 使用场景:自定义的UITableViewCell上有 ...
- LeetCode之“字符串”:最短回文子串
题目链接 题目要求: Given a string S, you are allowed to convert it to a palindrome by adding characters in f ...
- PS 图像调整算法——色调分离
色调分离的原理就是将R, G, B每个通道 0-255 的色调区间进行强制划分到给定的区间里去,所以色调会合并,最终的图像看起来颜色就是一块一块的. clc; clear all; close all ...
- JSP 知识基本
from:http://blog.csdn.net/caipeichao2/article/details/38589293 more:http://www.2cto.com/kf/web/jsp/4 ...
- bulk-load 装载HDFS数据到HBase
bulk-load的作用是用mapreduce的方式将hdfs上的文件装载到hbase中,对于海量数据装载入hbase非常有用,参考http://hbase.apache.org/docs/r0.89 ...