Python基础学习----数据存储

关注公众号“码农帮派”,查看更多系列技术文章:

 

Python中常用的数据存储的方式有:pickle模块,shelve模块,MySQL数据库,MongoDB数据库,SQLite轻量数据库,Excel表格存储等等。

(1)使用pickle模块进行数据存储

pickle是标准库中的模块,与之相同的是cpickle模块,cpickle是由c语言重写之后的,与pickle完全一致的模块,比pickle快。

(1-1)pickle的数据写入

pickle使用dump(obj, file, [protocol])函数将数据写入到文件中:

obj : 待写入的数据对象;

file : 要写入数据的文件;

protocol : 写入协议,默认为False或0,表示将会以ASCII格式保存对象数据,protocol=True时,表示以压缩的二进制格式保存对象数据。

 

# coding=utf-8
import pickle

list = [1,2,3,4,5,6,7]
f = open("pickle_tmp.dat", 'wb')
# pickle使用dump()函数,将数据写入到文件中
pickle.dump(list, f)
f.close()

执行代码之后,后生成一个pickle_tmp.dat的文件,并将数据写入到该文件中:

 

 

(1-2)pickle的数据读取

pickle模块使用load(file)函数反序列化读取文件数据。

 

# coding=utf-8
import pickle

f = open("pickle_tmp.dat", "rb")
result = pickle.load(f)
print type(result),result

打印结果:

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
<type 'list'> [1, 2, 3, 4, 5, 6, 7]

Process finished with exit code 0

 

 

 

(2)使用shelve模块进行数据读写

shelve也是标准库。

(2-2)shelve的数据写入

 

# coding=utf-8
import shelve

# 打开/创建shelve数据写入的文件
s = shelve.open("shelve_tmp.db")
# 下面是将不同type的数据写入到shelve数据文件中
s["name"] = 'mxd'
s["age"] = 23
s['clazz'] = ['Python', 'Java', 'NodeJS']
s['dict'] = {"date": '2016-10-20', 'place': 'hust'}
s.close()

执行代码之后,可以在文件系统中看到新创建的文件shelve_tmp.db文件:

 

 

(2-2)shelve的数据读取

 

# coding=utf-8
import shelve

# 打开/创建shelve数据写入的文件
s = shelve.open("shelve_tmp.db")
# 从shelve数据文件中读取数据
print s['name']
print s['age']
clazz = s['clazz']
print type(clazz), clazz
dict = s['dict']
print type(dict), dict

s.close()

打印结果:

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
mxd
23
<type 'list'> ['Python', 'Java', 'NodeJS']
<type 'dict'> {'date': '2016-10-20', 'place': 'hust'}

Process finished with exit code 0

【注意】shelve模块中, 通过 s['name'] = 'hust'  这一过程,若已存在"name"键时,则上面的操作是修改原有键对应的值,若没有"name"的键,则会增加新的键值对;但要是shevle中需要存储一个键值对,值是一个列表,现在需要更新列表的内容:

 

# coding=utf-8
import shelve

s = shelve.open("shelve_tmp.db")
s['list'] = ["hello"]
s["list"].append('hi')

print s['list'] # 设想的结果应该是: ['hello', 'hi']

打印结果:

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
['hello']

Process finished with exit code 0

我们发现结果并不是我们设想的那样,错误出现在shelve.open()函数上,此处需要多传入一些参数:

# coding=utf-8
import shelve

s = shelve.open("shelve_tmp.db", writeback=True)
s['list'] = ["hello"]
s["list"].append('hi')

print s['list'] # 设想的结果应该是: ['hello', 'hi']

打印结果:

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
['hello', 'hi']

Process finished with exit code 0

 

 

 

(3)MySQL数据库存储数据

在Ubuntu上,MySQL的安装为:

 

第一步: sudo apt-get install mysql-server
第二步: apt-get isntall mysql-client
第三步: sudo apt-get install libmysqlclient-dev

 

 

 

Python中提供了MySQLdb模块,可以让Python于MySQL数据库进行交互,MySQLdb不是Python的标准库,需要额外安装:

 

方法一:
1. sudo apt-get install build-essential python-dev libmysqlclient-dev
2. sudo apt-get install python-MySQLdb
方法二:
pip install mysql-python

 

 

 

使用MySQLdb模块可以链接MySQL数据库,并与之进行交互:

 

# coding=utf-8
import MySQLdb

# MySQLdb中的函数connect()可以实现数据库的链接
conn = MySQLdb.connect(host="localhost", user="root", passwd="root", db="mydb", port=3306, charset="utf8")
# MySQLdb.connect()得到链接对象,从中获取得到游标cursor
cur = conn.cursor()

通过MySQL.connect()函数获取得到MySQL数据库的链接对象,从该对象可以获得游标cursor对象,与MySQL数据库的对话,就是通过游标cursor来完成的。

 

数据库链接对象的常用方法

 

   方法      说明   
   commit()   数据库中表进行了修改之后,需要调用MySQL.connect()对象的commit()方法来提交保存当前的数据
   rollback()   有权限时,可以取消当前的操作,否则报错
   cursor([cursorclass])   返回链接的游标对象,通过游标对象对MySQL数据库进行操作
   close()关闭数据库的链接

 

数据库游标cursor常用方法

 

 

   方法      说明
   close()   关闭游标
   execute(query, [args])   执行一条sql语句
   executemany(query, seq)   对序列seq中的每一个参数执行一次sql语句
   fetchone()返回一条查询结果
   fetchall()返回所有查询结果
   fetchmany([size])返回size个结果
   nextset()移动到下一个结果
   scroll(value, mode="relative")   移动游标到指定的行,mode="relative"表示从当前行移动value条;mode="absolute"表示从第一行移动value条

 

(3-1)查询数据

 

 

# coding=utf-8
import MySQLdb

# MySQLdb中的函数connect()可以实现数据库的链接
conn = MySQLdb.connect(host="localhost", user="root", passwd="root", db="mydb", port=3306, charset="utf8")
# MySQLdb.connect()得到链接对象,从中获取得到游标cursor
cur = conn.cursor()

cur.execute("select * from user")
lines = cur.fetchall() # 获得全部结果

# 逐行打印结果
for line in lines:
    print line

 

打印结果:

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
(1L, u'Tom', 23L, u'male', u'student')
(2L, u'Kate', 27L, u'fema', u'teacher')

Process finished with exit code 0

 

【说明】游标的方法fetchone()方法每次得到当前游标所在位置上的结果集,同时会将游标移动到下一个结果集上,若要手动移动游标,则可以使用游标的nextset()方法,以及scroll()方法。

 

(3-2)插入数据

 

# coding=utf-8
import MySQLdb

# MySQLdb中的函数connect()可以实现数据库的链接
conn = MySQLdb.connect(host="localhost", user="root", passwd="root", db="mydb", port=3306, charset="utf8")
# MySQLdb.connect()得到链接对象,从中获取得到游标cursor
cur = conn.cursor()

# MySQL中插入数据的sql语句
sql = "insert into user(id, name, age, sex, job) values (null, %s, %s, %s, %s)"
# 执行MySQL插入数据的操作
cur.execute(sql, ('mxd', 23, 'male', 'student'))
# 此处需要调用connect的链接对象的commit()方法向数据库提交数据更新
conn.commit()

cur.execute('select * from user')
print cur.fetchall()

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
((1L, u'Tom', 23L, u'male', u'student'), 
 (2L, u'Kate', 27L, u'fema', u'teacher'), 
 (4L, u'mxd', 23L, u'male', u'student'))  # 成功插入了一条数据

Process finished with exit code 0

 

 

 

(3-3)更新数据

 

# coding=utf-8
import MySQLdb

# MySQLdb中的函数connect()可以实现数据库的链接
conn = MySQLdb.connect(host="localhost", user="root", passwd="root", db="mydb", port=3306, charset="utf8")
# MySQLdb.connect()得到链接对象,从中获取得到游标cursor
cur = conn.cursor()

# MySQl数据库数据更新的语句
sql = "update user set job=%s,age=%s where id=1"
# 执行数据库更新的操作
cur.execute(sql, ('teacher', 29))
conn.commit() # 更新数据库操作

cur.execute('select * from user')
print cur.fetchall()

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
((1L, u'Tom', 29L, u'male', u'teacher'), 
 (2L, u'Kate', 27L, u'fema', u'teacher'), 
 (4L, u'mxd', 23L, u'male', u'student'))

Process finished with exit code 0

 

 

 

【注意】

在数据库操作之后,为了节省内存,需要关闭游标对象和数据库链接对象。

 

cur.close()
conn.close()

 

(4)Mongo数据库存储数据

 

Mongo数据库是NoSQL数据库,Python中提供了pymongo模块来实现与Mongo数据库的交互,首先需要安装pymongo:

 

 
# 安装最新版本的pymongo模块 sudo pip install pymongo # 安装指定版本的pymongo(version2.8) sudo pip install pymongo==2.8

安装之后,可以使用pymongo.version来查看pymongo模块的版本:

 

安装之后,使用dir(pymongo)来查看pymongo中的方法和属性:

在Ubuntu上安装MongoDB:

 

# ubuntu安装MongoDB
sudo apt-get install mongodb

 

 

 

与MongoDB进行链接:

 

# coding=utf-8
import pymongo

# 与MongoDB建立链接
client = pymongo.MongoClient('localhost', 27017)
# MongoDB数据库中的数据库mydb建立链接
# mydb是自己创建的数据库
db = client.mydb
# 此处也可以使用 db = client['mydb']建立数据库的链接

# 显示数据库中所有文档的名称
print db.collection_names()

 打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
[u'system.indexes', u'user'] 

Process finished with exit code 0

【说明】上面的mydb是自己在MongoDB中建立的数据库,user是mydb数据库中的一个文档集合,数据是存储在user文档集合中的。

 

 

(4-1)查询数据

 

# coding=utf-8
import pymongo

# 与MongoDB建立链接
client = pymongo.MongoClient('localhost', 27017)
# MongoDB数据库中的数据库mydb建立链接
# mydb是自己创建的
db = client.mydb
# 此处也可以使用 db = client['mydb']建立数据库的链接

# 获取得到数据库mydb中的数据集合user对象
# 获取数据集合对象,还可以使用 user = db['user']
user = db.user
print type(user) # user的type为Collection

# 查询得到user数据集合对象中所有的数据
users = user.find()
for u in users:
    print u

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
<class 'pymongo.collection.Collection'>
{u'job': u'teacher', u'age': 23.0, u'_id': ObjectId('5809f27308f3d8ccaefcb17e'), u'name': u'Jim', u'sex': u'male'}
{u'job': u'student', u'age': 18.0, u'_id': ObjectId('5809f27708f3d8ccaefcb17f'), u'name': u'Mxd', u'sex': u'male'}

Process finished with exit code 0

 

 

 

可以将find()获得的结果集进行排序:

 

# coding=utf-8
import pymongo

# 与MongoDB建立链接
client = pymongo.MongoClient('localhost', 27017)
# MongoDB数据库中的数据库mydb建立链接
# mydb是自己创建的
db = client.mydb
# 此处也可以使用 db = client['mydb']建立数据库的链接

# 获取得到数据库mydb中的数据集合user对象
# 获取数据集合对象,还可以使用 user = db['user']
user = db.user

# 查询得到user数据集合对象中所有的数据
# pymongo.ASCENDING升序排序; pymongo.DESCENDING降序排序
users = user.find().sort("age", pymongo.ASCENDING) # 升序排序
for u in users:
    print u

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
<class 'pymongo.collection.Collection'>
{u'job': u'student', u'age': 18.0, u'_id': ObjectId('5809f27708f3d8ccaefcb17f'), u'name': u'Mxd', u'sex': u'male'}
{u'job': u'teacher', u'age': 23.0, u'_id': ObjectId('5809f27308f3d8ccaefcb17e'), u'name': u'Jim', u'sex': u'male'}

Process finished with exit code 0

 

 

 

数据集合中的find_one()函数可以查找到一条数据:

 

# coding=utf-8
import pymongo

# 与MongoDB建立链接
client = pymongo.MongoClient('localhost', 27017)
# MongoDB数据库中的数据库mydb建立链接
# mydb是自己创建的
db = client.mydb
# 此处也可以使用 db = client['mydb']建立数据库的链接

# 获取得到数据库mydb中的数据集合user对象
# 获取数据集合对象,还可以使用 user = db['user']
user = db.user

# 打印数据集合中数据的条数
print user.find().count()
# 打印数据集合中的第一条数据
print user.find_one()
# 打印name='Mxd'的结果
print user.find_one({'name':"Mxd"})

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
2
{u'job': u'teacher', u'age': 23.0, u'_id': ObjectId('5809f27308f3d8ccaefcb17e'), u'name': u'Jim', u'sex': u'male'}
{u'job': u'student', u'age': 18.0, u'_id': ObjectId('5809f27708f3d8ccaefcb17f'), u'name': u'Mxd', u'sex': u'male'}

Process finished with exit code 0

 

 

 

(4-2)增加数据

在数据集合中插入数据,调用数据集合对象的insert()进行数据的增加。

 

 
# coding=utf-8 import pymongo # 与MongoDB建立链接 client = pymongo.MongoClient('localhost', 27017) # MongoDB数据库中的数据库mydb建立链接 # mydb是自己创建的 db = client.mydb # 此处也可以使用 db = client['mydb']建立数据库的链接  # 获取得到数据库mydb中的数据集合user对象 # 获取数据集合对象,还可以使用 user = db['user'] user = db.user # 需要存储数据的集合 userInfo = {'name': 'Kate', 'age': 29, 'sex': 'female', 'job': 'teacher'} # 调用数据集合对象的insert()方法,插入数据 user.insert(userInfo) # 多条数据插入 userInfos = [{'name': 'Lilei', 'age': 19, 'sex': 'male', 'job': 'student'},  {'name': 'Lily', 'age': 18, 'sex': 'female', 'job': 'student'}] # 调用数据集合对象的insert()方法,插入多条数据 user.insert(userInfos) # 查看插入结果 results = user.find() for u in results: print u

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
{u'job': u'teacher', u'age': 23.0, u'_id': ObjectId('5809f27308f3d8ccaefcb17e'), u'name': u'Jim', u'sex': u'male'}
{u'job': u'student', u'age': 18.0, u'_id': ObjectId('5809f27708f3d8ccaefcb17f'), u'name': u'Mxd', u'sex': u'male'}
{u'job': u'teacher', u'_id': ObjectId('5809faeb64de7e29f8670465'), u'sex': u'female', u'age': 29, u'name': u'Kate'}
{u'job': u'student', u'_id': ObjectId('5809faeb64de7e29f8670466'), u'sex': u'male', u'age': 19, u'name': u'Lilei'}
{u'job': u'student', u'_id': ObjectId('5809faeb64de7e29f8670467'), u'sex': u'female', u'age': 18, u'name': u'Lily'}

Process finished with exit code 0

 

 

 

(4-3)更新数据

Python可以调用数据集合的update()函数进行数据的更新。

 

# coding=utf-8
import pymongo

# 与MongoDB建立链接
client = pymongo.MongoClient('localhost', 27017)
# MongoDB数据库中的数据库mydb建立链接
# mydb是自己创建的
db = client.mydb
# 此处也可以使用 db = client['mydb']建立数据库的链接

# 获取得到数据库mydb中的数据集合user对象
# 获取数据集合对象,还可以使用 user = db['user']
user = db.user

# 更新name='Mxd'的数据,通过$set修改器进行修改
user.update({'name': 'Mxd'}, {'$set': {'job': 'teacher', 'age': 29}})
# 打印name='Mxd'修改之后的结果
print user.find_one({'name': 'Mxd'})

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
{u'age': 29, u'_id': ObjectId('5809f27708f3d8ccaefcb17f'), u'sex': u'male', u'job': u'teacher', u'name': u'Mxd'}

Process finished with exit code 0

 

 

 

(4-4)删除数据

Python中调用数据集合的remove()函数删除数据:

 

# coding=utf-8
import pymongo

# 与MongoDB建立链接
client = pymongo.MongoClient('localhost', 27017)
# MongoDB数据库中的数据库mydb建立链接
# mydb是自己创建的
db = client.mydb
# 此处也可以使用 db = client['mydb']建立数据库的链接

# 获取得到数据库mydb中的数据集合user对象
# 获取数据集合对象,还可以使用 user = db['user']
user = db.user

# 删除name='Mxd'的数据
user.remove({'name': 'Mxd'})
# 打印name='Mxd'的数据
print user.find_one({'name': 'Mxd'})

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
None

Process finished with exit code 0

 

(5)Microsoft Excel表格存储数据

 

Python中提供opnepyxl模块进行Microsoft Excel表格数据的读写,在Ubuntu系统中需要首先安装openpyxl模块:

 

# 安装openpyxl模块
sudo pip install openpyxl

 

 

 

操作Excel文件对象:

 

#coding=utf-8
# 引入openpyxl模块
from openpyxl import Workbook
# 实例化Workbook,对其对象进行操作
# wb即是Excel对象,可以通过wb对象操作Excel文件对象
wb = Workbook()

 

 

 

每个Excel文件的操作涉及到sheet和cell两个对象。

(5-1)sheet的创建

Python可以使用openpyxl模块中的create_sheet()方法进行sheet的创建:

 

#coding=utf-8
# 引入openpyxl模块
from openpyxl import Workbook
# 实例化Workbook,对其对象进行操作
# wb即是Excel对象,可以通过wb对象操作Excel文件对象
wb = Workbook()

# 获取Excel表格中第一个sheet的操作对象
ws = wb.active

# 也可以在Excel中创建一个新的sheet
# wb.create_sheet([title], [index]) title是sheet的title,index是当前sheet的位置
# title默认为: "Sheet1", "Sheet2",....
ws_new = wb.create_sheet()

 

 

 

(5-2)sheet对象常用的操作

 

 
#coding=utf-8 # 引入openpyxl模块 from openpyxl import Workbook # 实例化Workbook,对其对象进行操作 # wb即是Excel对象,可以通过wb对象操作Excel文件对象 wb = Workbook() # 获取Excel表格中第一个sheet的操作对象 ws = wb.active # 创建一个默认的sheet wb.create_sheet() # 修改ws这个sheet对象的title ws.title = "python"  # 打印查看wb中sheet对象的名称 print wb.get_sheet_names() # 获取sheet-title='python'的sheet对象 ws_0 = wb.get_sheet_by_name('python') # 也可以通过下面的方法获取 ws_1 = wb['python']

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
[u'python', 'Sheet1']

Process finished with exit code 0

 

 

 

(5-3)操作cell

在Sheet中的cell中可以存储具体的数据。

 

#coding=utf-8
# 引入openpyxl模块
from openpyxl import Workbook
# 实例化Workbook,对其对象进行操作
# wb即是Excel对象,可以通过wb对象操作Excel文件对象
wb = Workbook()

# 获取Excel表格中第一个sheet的操作对象
ws = wb.active
# 修改ws这个sheet对象的title
ws.title = "python"
# 获取sheet-title='python'的sheet对象
ws_0 = wb.get_sheet_by_name('python')

# 获取该sheet对象ws_0中位置B4的单元格
b4 = ws_0['B4']

# 修改B4单元格的内容
ws_0['B4'] = '2333'

# 获取sheet对象的B4单元格的数值
# 也可以使用这种方式获取: ws_0['B4'].value
print b4.value
print ws_0['B4'].value

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
2333
2333

Process finished with exit code 0

 

 

 

(5-4)其他相关操作

(5-4-1)获取cell切片集合

 

#coding=utf-8
# 引入openpyxl模块
from openpyxl import Workbook
# 实例化Workbook,对其对象进行操作
# wb即是Excel对象,可以通过wb对象操作Excel文件对象
wb = Workbook()

# 获取Excel表格中第一个sheet的操作对象
ws = wb.active
# 修改ws这个sheet对象的title
ws.title = "python"
# 获取sheet-title='python'的sheet对象
ws_0 = wb.get_sheet_by_name('python')

# 获得单元格切片
cells = ws['A1':'C3']
print cells

打印结果:(以元组的方式返回)

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
((<Cell python.A1>, <Cell python.B1>, <Cell python.C1>), 
(<Cell python.A2>, <Cell python.B2>, <Cell python.C2>), 
(<Cell python.A3>, <Cell python.B3>, <Cell python.C3>))

Process finished with exit code 0

 

 

 

(5-4-2)按照行/列的方式查看sheet表格

 

#按照row,按照一列一列的顺序获得元组
print ws_0.rows

# 按照columns,按照一行一行的顺序获得元组
print ws_0.columns

 

 

 

(5-4-3)在Sheet表格中添加数据

 

#coding=utf-8
# 引入openpyxl模块
from openpyxl import Workbook
# 实例化Workbook,对其对象进行操作
# wb即是Excel对象,可以通过wb对象操作Excel文件对象
wb = Workbook()

# 获取Excel表格中第一个sheet的操作对象
ws = wb.active
# 修改ws这个sheet对象的title
ws.title = "python"
# 获取sheet-title='python'的sheet对象
ws_0 = wb.get_sheet_by_name('python')

# 通过一个切片,指定Sheet表格中一个cell区域
rows = ws['A1': 'D10']
# 下面味这个区域的cell赋值
i = 1
for row in rows:
    for cell in row:
        cell.value = i
        i += 1

print "A10=",ws['A10'].value
print "D1=",ws['D1'].value

 

打印结果:

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
A10= 37
D1= 4

Process finished with exit code 0

 

 

 

(5-5)保存Excel文件

【说明】上面的操作,是将新创建的Excel表格存储在内存中操作,在结束操作之后,需要保存一下Excel表格,以便数据的持久化存储。

 

# 保存Excel文件
wb.save("1024.xlsx")

在命令行中,使用ls查看文件系统:

 

打开Excel文件,查看内容:

 

(5-6)读取已存在的Excel文件

 

#coding=utf-8
# 引入openpyxl模块
from openpyxl import load_workbook
# 读入Excel文件
wb = load_workbook("1024.xlsx")

# 打印Excel文件的所有sheet的title
print wb.get_sheet_names()

# 在Excel文件对象中获取title='python'的sheet对象
ws = wb['python']

# 按照两种顺序打印sheet表格
print "按照rows顺序打印:"
for row in ws.rows:
    for cell in row:
        print cell.value,

print
print "按照columns顺序打印:"
for col in ws.columns:
    for cell in col:
        print cell.value,

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test.py
[u'python']
按照rows顺序打印:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
按照columns顺序打印:
1 5 9 13 17 21 25 29 33 37 2 6 10 14 18 22 26 30 34 38 3 7 11 15 19 23 27 31 35 39 4 8 12 16 20 24 28 32 36 40

Process finished with exit code 0

 

【补充】Excel表格的处理,处理openpyxl模块之外,还可以使用xlsxwriter模块,xlrd模块,xlwt模块进行处理。

 

 

(6)SQLite数据库

SQLite是一种小型的关系型数据库,不需要服务器,零配置就可以进行数据的存储,Python标准库中的sqlite3可以用来操作SQLite数据库。

 

#coding=utf-8
import sqlite3
# 数据库的链接
# 若存在123.db,则直接链接该数据库,若不存在,则首先创建
conn = sqlite3.connect('123.db')
# 获得游标对象
cur = conn.cursor()

上面使用Python标准库sqlite3进行SQLite数据库的链接,执行之后可以看到在当前文件夹中生成了123.db的数据库文件,当然也可以指定文件存在/创建的路径:

 

 

mxd@mxd-ThinkPad:~/文档/WorkPlace/python/PythonStudy/test$ ls
123.db  __init__.py  test.py

 

 

 

(6-1)表的创建

 

#coding=utf-8
import sqlite3
# 数据库的链接
# 若存在123.db,则直接链接该数据库,若不存在,则首先创建
conn = sqlite3.connect('123.db')
# 获得游标对象
cur = conn.cursor()

# 创建表books
sql_create = "create table books(title text, name text, author text)"
# 调用游标对象的execute()方法执行sql语句
cur.execute(sql_create)
# 更新数据库
conn.commit()

执行之后,查看123.db数据库文件:

 

【说明】在Ubuntu系统下可以使用: 

sudo apt-get install sqlitebrowser

命令来安装sqlitebrowser用于查看SQLite数据库文件,安装好之后,在123.db所在的目录中使用:

sqlitebrowser 123.db 

命令,既可以看到上面的情况。

 

(6-2)数据存储

 

#coding=utf-8
import sqlite3
# 数据库的链接
# 若存在123.db,则直接链接该数据库,若不存在,则首先创建
conn = sqlite3.connect('123.db')
# 获得游标对象
cur = conn.cursor()
# 表中插入数据
sql_insert = 'insert into books values("computer", "Python", "mxd")'
# 利用游标对象的execute()方法执行SQL语句
cur.execute(sql_insert)
# 更新数据库
conn.commit()

执行完上面的语句之后:

 

(6-3)数据查询

 

#coding=utf-8
import sqlite3
# 数据库的链接
# 若存在123.db,则直接链接该数据库,若不存在,则首先创建
conn = sqlite3.connect('123.db')
# 获得游标对象
cur = conn.cursor()
# 查询数据
sql_sel = "select * from books"
# 使用游标对象的execute()方法执行SQL语句
cur.execute(sql_sel)
# fetchall() 方法查看所有的结果集
print cur.fetchall()

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test/test.py
[(u'computer', u'Python', u'mxd')]

Process finished with exit code 0

 

【说明】游标对象的fetchall()以列表返回所有的结果集,游标对象的fetchone()方法只返回第一个匹配到的结果集。

 

(6-4)批量导入数据

 

#coding=utf-8
import sqlite3
# 数据库的链接
# 若存在123.db,则直接链接该数据库,若不存在,则首先创建
conn = sqlite3.connect('123.db')
# 获得游标对象
cur = conn.cursor()
# 批量导入数据
books = [("computer", "Java", "mmd"), ("NetWork", "NodeJS", "mmx"),
         ("NetWork", "PHP", "mma")]
# SQL语句
sql_adds = "insert into books values(?,?,?)"
# 使用游标对象的executemany()方法执行SQL语句
cur.executemany(sql_adds, books)
# 更新数据库
conn.commit()

#---------查看结果
cur.execute("select * from books")
print cur.fetchall()

cur.close()
conn.close()

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test/test.py
[(u'computer', u'Python', u'mxd'), (u'computer', u'Java', u'mmd'), (u'NetWork', u'NodeJS', u'mmx'), (u'NetWork', u'PHP', u'mma')]

Process finished with exit code 0

 

 

 

利用sqlitebrowser工具查看SQLite数据库文件123.db:

 

(6-5)数据更新

 

#coding=utf-8
import sqlite3
# 数据库的链接
# 若存在123.db,则直接链接该数据库,若不存在,则首先创建
conn = sqlite3.connect('123.db')
# 获得游标对象
cur = conn.cursor()
# 更新数据
sql_update = "update books set title='{0}' where name='{1}'".format('NetWork', 'Python')
# 使用游标对象的execute()方法执行SQL语句
cur.execute(sql_update)
# 更新数据库
conn.commit()

# ------查看数据库
cur.execute("select * from books")
print cur.fetchall()

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test/test.py
[(u'NetWork', u'Python', u'mxd'), (u'computer', u'Java', u'mmd'), (u'NetWork', u'NodeJS', u'mmx'), (u'NetWork', u'PHP', u'mma')]

Process finished with exit code 0

使用sqlitebrowser工具查看123.db文件:

 

 

(6-6)删除数据

 

#coding=utf-8
import sqlite3
# 数据库的链接
# 若存在123.db,则直接链接该数据库,若不存在,则首先创建
conn = sqlite3.connect('123.db')
# 获得游标对象
cur = conn.cursor()
# 删除数据
sql_del = "delete from books where author='{0}'".format('mxd')
# 使用游标对象的execute()方法执行SQL语句
cur.execute(sql_del)
# 更新数据库
conn.commit()

# ------查看数据库
cur.execute("select * from books")
print cur.fetchall()

打印结果:

 

 

/usr/bin/python2.7 /home/mxd/文档/WorkPlace/python/PythonStudy/test/test.py
[(u'computer', u'Java', u'mmd'), (u'NetWork', u'NodeJS', u'mmx'), (u'NetWork', u'PHP', u'mma')]

Process finished with exit code 0

删除成功,需要注意的是,在执行完操作之后,需要尽量关闭游标对象,数据库链接对象:

 

 

# 关闭游标对象
cur.close()
# 关闭数据库链接对象
conn.close()

 

 

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值