python连接sqlserver 多条sql语句后提交_利用python操作sqllite

SQLite3 可使用 sqlite3 模块与 Python 进行集成。sqlite3 模块是由 Gerhard Haring 编写的。它提供了一个与 PEP 249 描述的 DB-API 2.0 规范兼容的 SQL 接口。您不需要单独安装该模块,因为 Python 2.5.x 以上版本默认自带了该模块,所以使用时直接导入即可。

sqlite的基础教程可以参考SQLite - Python官方文档下面举一个简单的例子:1、插入数据rollback()用于事务回滚;出现错误时可以使用回滚;

#coding:utf-8import sqlite3#使用connect()方法创建或打开数据库,指定数据库的路径,如果存在直接打开,不存在则创建一个新的数据库;
con = sqlite3.connect('E:\\sqlite\\test.db')#con = sqlite3.connect(':memory:') 在内存中创建数据库#通过cursor方法创建一个游标对象
cur = con.cursor()#创建表person
cur.execute(' CREATE TABLE person (id integer primary key,name varchar(20),age integer)')#插入数据
data="0,'sara',20"
cur.execute(' INSERT INTO person VALUES (%s)'%data) #直接构造插入的SQL的语句,但是这种不安全,容易导致SQL注入,可以使用占位符“?”规避
cur.execute(' INSERT OR IGNORE INTO person VALUES (?,?,?)',(1,'迈克',24)) #使用占位符“?”更安全#使用executemany执行多条SQL语句,使用executeman()比循环使用execute()使用高效
cur.executemany(' INSERT INTO person VALUES (?,?,?)',[(2,'开心麻花',30),(3,'jack',50)])#插入数据不会立即生效,需要commit()提交;
con.commit()#关闭数据库连接
con.close()

执行结果:

ec8b5a06ccfe4a82096f8514117b5860.png
1、插入数据

2、查询数据fetchone()从结果中取一条记录,并将游标指向下一条记录;fetchmany()从结果中取多条记录;fetchall()从结果中取出全部记录;scroll()用于游标滚动;

1)查询全部数据

#coding:utf-8import sqlite3#使用connect()方法创建或打开数据库,指定数据库的路径,如果存在直接打开,不存在则创建一个新的数据库;
con = sqlite3.connect('E:\\sqlite\\test.db')#con = sqlite3.connect(':memory:') 在内存中创建数据库#通过cursor方法创建一个游标对象
cur = con.cursor()#创建表person
cur.execute(' CREATE TABLE person (id integer primary key,name varchar(20),age integer)')#插入数据
data="0,'sara',20"
cur.execute(' INSERT INTO person VALUES (%s)'%data) #直接构造插入的SQL的语句,但是这种不安全,容易导致SQL注入,可以使用占位符“?”规避
cur.execute(' INSERT OR IGNORE INTO person VALUES (?,?,?)',(1,'迈克',24)) #使用占位符“?”更安全#使用executemany执行多条SQL语句,使用executeman()比循环使用execute()使用高效
cur.executemany(' INSERT INTO person VALUES (?,?,?)',[(2,'开心麻花',30),(3,'jack',50)])# 查询表person的所有数据
cur.execute('SELECT * FROM person')#fetchall()获取所有数据,返回一个二维的列表
res = cur.fetchall()print(res)for line in res:print(line)#插入数据不会立即生效,需要commit()提交;
con.commit()#关闭数据库连接
con.close()

执行结果:

dcd40f436518e98bee99491a107f8631.png
2、查询全部数据

2)查询单个数据

#coding:utf-8import sqlite3#使用connect()方法创建或打开数据库,指定数据库的路径,如果存在直接打开,不存在则创建一个新的数据库;
con = sqlite3.connect('E:\\sqlite\\test.db')#con = sqlite3.connect(':memory:') 在内存中创建数据库#通过cursor方法创建一个游标对象
cur = con.cursor()#创建表person
cur.execute(' CREATE TABLE person (id integer primary key,name varchar(20),age integer)')#插入数据
data="0,'sara',20"
cur.execute(' INSERT INTO person VALUES (%s)'%data) #直接构造插入的SQL的语句,但是这种不安全,容易导致SQL注入,可以使用占位符“?”规避
cur.execute(' INSERT OR IGNORE INTO person VALUES (?,?,?)',(1,'迈克',24)) #使用占位符“?”更安全#使用executemany执行多条SQL语句,使用executeman()比循环使用execute()使用高效
cur.executemany(' INSERT INTO person VALUES (?,?,?)',[(2,'开心麻花',30),(3,'jack',50)])#fetchone()获取其中的一个结果,返回一个元组
cur.execute('SELECT * FROM person')
res = cur.fetchone()print(res)#插入数据不会立即生效,需要commit()提交;
con.commit()#关闭数据库连接
con.close()

执行结果:

319bd045739c5eee683f293e7e396510.png
2、查询单个数据

3、修改和删除数据

#coding:utf-8import sqlite3#使用connect()方法创建或打开数据库,指定数据库的路径,如果存在直接打开,不存在则创建一个新的数据库;
con = sqlite3.connect('E:\\sqlite\\test.db')#con = sqlite3.connect(':memory:') 在内存中创建数据库#通过cursor方法创建一个游标对象
cur = con.cursor()#创建表person
cur.execute(' CREATE TABLE person (id integer primary key,name varchar(20),age integer)')#插入数据
data="0,'sara',20"
cur.execute(' INSERT INTO person VALUES (%s)'%data) #直接构造插入的SQL的语句,但是这种不安全,容易导致SQL注入,可以使用占位符“?”规避
cur.execute(' INSERT OR IGNORE INTO person VALUES (?,?,?)',(1,'迈克',24)) #使用占位符“?”更安全#使用executemany执行多条SQL语句,使用executeman()比循环使用execute()使用高效
cur.executemany(' INSERT INTO person VALUES (?,?,?)',[(2,'开心麻花',30),(3,'jack',50)])#修改数据
cur.execute('UPDATE person SET name=? WHERE id=?',('小明',1))#删除数据
cur.execute('DELETE FROM person WHERE id=?',(0,))#插入数据不会立即生效,需要commit()提交;
con.commit()#关闭数据库连接
con.close()

执行结果:

4d7b3674e08b3709649429ee03e5fd0f.png
3、修改和删除后的数据

特别注意:1、执行完数据库操作后必须要关闭数据库;2、插入或修改中文数据时,如果出现乱码,可尝试在中文字符串前加“u”

下面是用之前天气的例子存到sqlite

import requestsfrom lxml import etreeimport jsonimport sqlite3#使用connect()方法创建或打开数据库,指定数据库的路径,如果存在直接打开,不存在则创建一个新的数据库;
con = sqlite3.connect('E:\\sqlite\\tianqi.db')#con = sqlite3.connect(':memory:') 在内存中创建数据库#通过cursor方法创建一个游标对象
cur = con.cursor()#创建表person
cur.execute(' CREATE TABLE shenzhen (date,date2,history_rain,history_max,history_min,tmax,tmin,time,w1,wd1,alins,als)')class Weather():
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36','Referer': 'http://www.weather.com.cn/weather40d/101280601.shtml'
}# 新建列表,用来存储获取的数据
all_info = []def __init__(self):pass# 获取一年的天气数据def get_data(self):global year
month = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']for i in month:
url = 'http://d1.weather.com.cn/calendar_new/' + str(year) + '/101280601_' + str(year) + str(
i) + '.html?_=1496558858156'
html = requests.get(url, headers=self.headers).contentglobal datas
datas = json.loads(html[11:])self.get_info()# 获取天气的具体数据def get_info(self):for data in datas:if data['date'][:4] == year:
date = data['date']
date2 = data['nlyf'] + data['nl']
history_rain = data['hgl']
history_max = data['hmax']
history_min = data['hmin']
tmax = data['max']
tmin = data['min']
time = data['time']
w1 = data['w1']
wd1 = data['wd1']
alins = data['alins']
als = data['als']#先把去重的数据存储到列表all_info
info = (date,date2,history_rain,history_max,history_min,tmax,tmin,time,w1,wd1,alins,als )if info not in self.all_info:self.all_info.append(info)#把数据存到sqlitedef store_sqlite(self):self.get_data()for one_info in self.all_info:
cur.execute(' INSERT OR IGNORE INTO shenzhen VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',one_info)
con.commit()if __name__ == '__main__':
year = '2017'
tianqi = Weather()
tianqi.store_sqlite()# 关闭数据库连接
con.close()

运行结果:

6bc019eba51884657fc26daff4ad2e69.png
天气

sqlite的可视化工具:SQLite Expert Professional

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值