python 操作sqlite数据库
'''SQLite数据库是一款非常小巧的嵌入式开源数据库软件,也就是说
没有独立的维护进程,所有的维护都来自于程序本身。
在python中,使用sqlite3创建数据库的连接,当我们指定的数据库文件不存在的时候
连接对象会自动创建数据库文件;如果数据库文件已经存在,则连接对象不会再创建
数据库文件,而是直接打开该数据库文件。
连接对象可以是硬盘上面的数据库文件,也可以是建立在内存中的,在内存中的数据库
执行完任何操作后,都不需要提交事务的(commit)
创建在硬盘上面: conn = sqlite3.connect('e:\\test.db')
创建在内存上面: conn = sqlite3.connect('memory:')
下面我们一硬盘上面创建数据库文件为例来具体说明:
conn = sqlite3.connect('e:\\test.db')
其中conn对象是数据库链接对象,而对于数据库链接对象来说,具有以下操作:
commit() --事务提交
rollback() --事务回滚
close() --关闭一个数据库链接
cursor() --创建一个游标
cu = conn.cursor()
这样我们就创建了一个游标对象:cu
在sqlite3中,所有sql语句的执行都要在游标对象的参与下完成
对于游标对象cu,具有以下具体操作:
execute() --执行一条sql语句
executemany() --执行多条sql语句
close() --游标关闭
fetchone() --从结果中取出一条记录
fetchmany() --从结果中取出多条记录
fetchall() --从结果中取出所有记录
scroll() --游标滚动
'''
# -*- coding: utf-8 -*-
import sqlite3
import os
class SqliteDB:
#是否打印sql
print_sql = True
#数据库连接
sqlite_Conn = None
def __init__(self,dbFile_path):
'''初始化数据库文件路径'''
filepath = unicode(dbFile_path,'utf8')
self.sqlite_Conn = self.get_Conn(filepath)
def get_Conn(self,dbFile_path):
'''获取到数据库的连接对象,参数为数据库文件的绝对路径
如果传递的参数是存在,并且是文件,那么就返回硬盘上面改
路径下的数据库文件的连接对象;否则,返回内存中的数据接
连接对象'''
if os.path.exists(dbFile_path) and os.path.isfile(dbFile_path):
print('硬盘上面:[{}]'.format(dbFile_path))
return sqlite3.connect(dbFile_path)
else:
print('内存上面:[:memory:]')
return sqlite3.connect(':memory:')
def commit(self):
'''提交数据库事务'''
if self.sqlite_Conn is not None:
self.sqlite_Conn.commit()
def get_Cursor(self):
'''
该方法是获取数据库的游标对象,参数为数据库的连接对象
如果数据库的连接对象不为None,则返回数据库连接对象所创
建的游标对象;否则返回一个游标对象,该对象是内存中数据
库连接对象所创建的游标对象
'''
if self.sqlite_Conn is not None:
return self.sqlite_Conn.cursor()
else:
return self.sqlite_Conn.cursor()
def close_Cursor(self,cursor):
'''关闭数据库游标对象和数据库连接对象'''
try:
if cursor is not None:
cursor.close()
finally:
if cursor is not None:
cursor.close()
################################################################
#创建表,删除表操作
################################################################
def create_Table(self, strSql):
'''创建数据库表:'''
if strSql is not None and strSql != '':
cursor = self.get_Cursor()
if self.print_sql:
print('执行sql:[{}]'.format(strSql))
cursor.execute(strSql)
self.commit()
print('创建数据库表成功!')
self.close_Cursor(cursor)
else:
print('the [{}] is empty or equal None!'.format(strSql))
def drop_Table(self,table):
'''如果表存在,则删除表,如果表中存在数据的时候,使用该
方法的时候要慎用!'''
if table is not None and table != '':
strSql = 'DROP TABLE IF EXISTS ' + table
if self.print_sql:
print('执行sql:[{}]'.format(strSql))
cursor = self.get_Cursor()
cursor.execute(strSql)
self.commit()
print('删除数据库表[{}]成功!'.format(table))
self.close_Cursor(cursor)
else:
print('the [{}] is empty or equal None!'.format(strSql))
#####################################################################
#数据库操作
#####################################################################
def insert_MultiData(self,strSql, data):
'''插入数据'''
if strSql is not None and strSql != '':
if data is not None:
cursor = self.get_Cursor()
for d in data:
if self.print_sql:
print('执行sql:[{}],参数:[{}]'.format(strSql, d))
cursor.execute(strSql, d)
self.commit()
self.close_Cursor(cursor)
else:
print('the [{}] is empty or equal None!'.format(strSql))
def insert_Data(self,strSql):
'''插入数据'''
if strSql is not None and strSql != '':
cursor = self.get_Cursor()
print('执行sql:[{}]'.format(strSql))
cursor.execute(strSql)
self.commit()
self.close_Cursor(cursor)
else:
print('the [{}] is empty or equal None!'.format(strSql))
def get_All_Item(self,strSql):
'''查询所有数据'''
if strSql is not None and strSql != '':
cursor = self.get_Cursor()
if self.print_sql:
print('执行sql:[{}]'.format(strSql))
cursor.execute(strSql)
listR = cursor.fetchall()
self.close_Cursor(cursor)
return listR
else:
print('the [{}] is empty or equal None!'.format(strSql))
return None
def get_One_Item(self,strSql, data):
'''查询一条数据'''
if strSql is not None and strSql != '':
if data is not None:
#Do this instead
d = (data,)
cursor = self.get_Cursor()
if self.print_sql:
print('执行sql:[{}],参数:[{}]'.format(strSql, data))
cursor.execute(strSql, d)
r = cursor.fetchall()
if len(r) > 0:
for e in range(len(r)):
print(r[e])
else:
print('the [{}] equal None!'.format(data))
else:
print('the [{}] is empty or equal None!'.format(strSql))
def update_Data(self,strSql, data):
'''更新数据'''
if strSql is not None and strSql != '':
if data is not None:
cursor = self.get_Cursor()
for d in data:
if self.print_sql:
print('执行sql:[{}],参数:[{}]'.format(strSql, d))
cursor.execute(strSql, d)
self.commit()
self.close_Cursor(cursor)
else:
print('the [{}] is empty or equal None!'.format(strSql))
def delete_multiData(self,strSql, data):
'''删除多条sql数据'''
if strSql is not None and strSql != '':
if data is not None:
cursor = self.get_Cursor()
for d in data:
if self.print_sql:
print('执行sql:[{}],参数:[{}]'.format(strSql, d))
cursor.execute(strSql, d)
self.commit()
self.close_Cursor(cursor)
else:
print('the [{}] is empty or equal None!'.format(strSql))
def delete_Data(self,strSql):
'''删除一条sql数据'''
if strSql is not None and strSql != '':
if self.print_sql:
print('执行sql:[{}]'.format(strSql))
cursor = self.get_Cursor()
cursor.execute(strSql)
self.commit()
self.close_Cursor(cursor)
else:
print('the [{}] is empty or equal None!'.format(strSql))
#########################################################################
#测试代码
#########################################################################
db = SqliteDB('e:\\test.db')
#删除数据表
db.drop_Table('person')
#创建数据库表
create_table_sql = '''CREATE TABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`gender` varchar(4) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
)'''
db.create_Table(create_table_sql)
#删除数据、
delSql='delete from person '
db.delete_Data(delSql)
#插入数据测试,插入一条语句
insert_sql ='''INSERT INTO person VALUES (3, 'xiaoli', '女', 18, '山东')'''
db.insert_Data(insert_sql)
#插入数据测试,插入多条语句
insert_sql = '''INSERT INTO person values (?, ?, ?, ?, ?)'''
'''
data = [[1, 'xiaowang', u'男', 20, u'广东'],
[2, 'xiaozhang', u'男', 22, u'河南'],
[3, 'xiaoli', u'男', 18, u'山东'],
[4, 'xiaoliu', u'女', 21, u'山西']]
'''
data = [[1, 'xiaowang', '男', 20, '广东'],
[2, 'xiaozhang', '男', 22, '河南'],
[3, 'xiaoli', '男', 18, '山东'],
[4, 'xiaoliu', '女', 21, '山西']]
for item in data:
item[2] = unicode(item[2],'utf8')
item[4] = unicode(item[4],'utf8')
db.insert_MultiData(insert_sql,data)
#查询数据
print db.get_All_Item('select * from person')
python 操作sqlite数据库的更多相关文章
- Python操作sqlite数据库小节
学习了Python操作sqlite数据库,做一个小结,以备后用. import sqlite3import os# 进行数据库操作时,主要是参数如何传输try:# 链接数据库conn=sqlite3. ...
- Python操作SQLite数据库的方法详解
Python操作SQLite数据库的方法详解 本文实例讲述了Python操作SQLite数据库的方法.分享给大家供大家参考,具体如下: SQLite简单介绍 SQLite数据库是一款非常小巧的嵌入式开 ...
- python操作sqlite数据库
root@cacti:~/box# cat convert.py #!/usr/bin/env python import sqlite3,time,rrdtool,os def boxstatus( ...
- Python 操作 SQLite 数据库
写在之前 SQLite 是一个小型的关系型数据库,它最大的特点在于不需要单独的服务.零配置.我们在之前讲过的两个数据库,不管是 MySQL 还是 MongoDB,都需要我们安装.安装之后,然后运行起来 ...
- 8.1 使用Python操作SQLite数据库
SQLite是内嵌在Python中的轻量级.基于磁盘文件袋额数据库管理系统,不需要安装和配置服务,支持使用SQL语句来访问数据库.该数据库使用C语言开发,支持大多数SQL91标准,支持原子的.一致的. ...
- Python 操作sqlite数据库及保存查询numpy类型数据(二)
# -*- coding: utf-8 -*- ''' Created on 2019年3月6日 @author: Administrator ''' import sqlite3 import nu ...
- Python 操作sqlite数据库及保存查询numpy类型数据(一)
# -*- coding: utf-8 -*- ''' Created on 2019年3月6日 @author: Administrator ''' import sqlite3 import nu ...
- [python]用Python进行SQLite数据库操作
用Python进行SQLite数据库操作 1.导入Python SQLITE数据库模块 Python2.5之后,内置了SQLite3,成为了内置模块,这给我们省了安装的功夫,只需导入即可~ ]: u ...
- Windows下安装MySQLdb, Python操作MySQL数据库的增删改查
这里的前提是windows上已经安装了MySQL数据库,且配置完成,能正常建表能操作. 在此基础上仅仅需安装MySQL-python-1.2.4b4.win32-py2.7.exe就ok了.仅仅有1M ...
随机推荐
- posix thread互斥量
互斥量 互斥量(Mutex)是“mutual exclusion”的缩写.互斥量是实现线程同步,和保护同时写共享数据的主要方法.使用互斥量的典型顺序如下:1. 创建和初始一个互斥量 2. 多个线程尝试 ...
- Freemarker 输出$和html标签等特殊符号
场景:程序员都不喜欢看文档,而更喜欢抄例子.所以,我们把平台组的组件都做成例子供别人参考.我们前端展示层使用的是freemarker,所以 遇到这个问题,比如我们要让前端显示freemarker自己的 ...
- C#.net在后台执行javascript
string script = string.Format("<script type='text/javascript' >alert('{0}');</script&g ...
- nopCommerce的配置以及汉化
这里给大家一些链接,是关于nopCommerce的一些介绍: nopCommerce的源代码 关于nopcommerce Nopcommerce中文资源 第一步 配置nopCommerce 先上一张 ...
- 【转】ASP.NET MVC 使用 FluentScheduler 定时器计划任务
MacBook Pro 只有四个 USB Type-C 接口是否错了? 一项新技术的诞生总会对已存在的事物造成冲击或影响,如果大家都害怕冲击与影响,那这个世界永远像现在不变就行了,大家都好好的,待在自 ...
- union判断CPU是little-endian还是big-endian存储
利用联合体的特殊存储方式,便能检测出来cpu所使用的事big-endian或者是little-endian的存储方式. 1.判断系统是Big liden 或者是little ledin 方法1:in ...
- 读取tomcat下的文件夹路径
背景:测试的为了每次部署时清缓存,将temp文件夹也删了,导致系统中有些excel导出功能用不了. 解决:新建一个监听文件,在系统启动时,判断temp文件夹是否存在,不存在就新建. temp文件夹的作 ...
- iOS Core Animation学习总结(3)--动画的基本类型
一. CABasicAnimation (基础动画) 移位: CABasicAnimation *animation = [CABasicAnimation animation]; //keyPath ...
- (转)linux下mysql的安装过程
最近在linux安装了mysql,根据网上收集的资料和个人的操作过程,大概做了个整理,以便以后进行参考回顾. 1.下载mysql-5.1.36.tar.gz,并且解压. tar -xzvf mysql ...
- LNK1123: 转换到 COFF 期间失败: 文件无效或损坏[汇总]
目前有两种方式可用于解决: 1. 微软官方的一个解决方案: http://support.microsoft.com/kb/320216/zh-cn 发现是嵌入清单的问题,于是对该工程以及所有依赖工程 ...