程序在执行的过程中会产生一些数据,一般情况下会将数据保存在磁盘中。其中最简单的方法就是将数据写入到某个文件中,就是将存储的对象格式化(或者叫做序列化)。
将数据存入文件
pickle
模块:将对象的数据写入文件和从文件中读取数据shevle
模块:相比于pickle
模块功能更多,更全面。
pickle模块
import pickle
list1 = [1,2,3,4,5]
f = open("file1.txt", "wb")
pickle.dump(list1, f)
f.close()
list1 = pickle.load(open("file1.txt", "rb"))
list1
shelve模块
import shelve
s = shelve.open("file2.txt")
s["name"] = "shenzhen"
s["language"] = "python"
s["age"] = 28
s["contents"] = {"first": "base knowledge", "second": "day day up"}
s.close()
s = shelve.open("file2.txt", writeback=True)
name = s["name"]
print(name)
age = s["age"]
print(age)
contents = s["contents"]
print(contents)
shenzhen
28
{'first': 'base knowledge', 'second': 'day day up'}
for k in s:
print(k,s[k])
name shenzhen
language python
age 28
contents {'first': 'base knowledge', 'second': 'day day up'}
操作数据库
三种主流的数据库:
- 关系型数据库:
MySQL、SQL server、Oracle
- 非关系型数据库:
MongoDB、BigTable、Redis
- 键值数据库:
Apache Cassandra、LevelDB
MySQL数据库
MySQL
属于关系型数据库。数据库表是一系列二维数组的集合,用来代表和存储对象之间的关系,由纵向的列和横向的行组成。MySQL
数据端口是3306
。Ubuntu
中安装MySQL
数据库的安装步骤见笔者札记
MySQL札记1_ubuntu18.04安装MySQL5.7
sudo apt-get install mysql
mysql -uroot -p
show databases;
use msyql;
show tables;
pymysql模块
安装
sudo pip3 install PyMySQL
import pymysql
创建数据库
create database bookdb character set utf8;
连接pymysql
使用模块的connect()
进行连接:
- host:主机名或者IP地址
- port:默认是
3306
- user:用户名
- passwd:
user
账户登录mysql
的密码 - db:创建的数据库
- charset:防止中文出错,编码格式设置为
charset="utf8"
import pymysql
conn = pymysql.connect(host=“localhost”, port=3306, user="root", passwd="123456", db="bookdb", charset="utf8")
操作数据库
Python
建立了和数据库的连接,实际上就是建立了一个pymysql.connect()
的实例对象,或者称之为连接对象。Python
就是通过连接对象和数据库进行对话。pymysql.connect()
实例对象的方法有:
commit
:提交数据rollback
:如果有权限,取消当前的操作,否则会报错cursor([cursorclass])
:返回连接的游标对象,执行SQL语句close()
:关闭连接
游标对象cur的操作方法
import pymysql
conn = pymysql.connect(host=“localhost”, port=3306, user="root", passwd="123456", db="bookdb", charset="utf8")
cur = conn.cursor()
cur.execute("insert into users (username, passwd, email) values (%s, %s, %s)", ("python", "123456", "python@gmail.com"))
cur.executemany("insert into users (username, passwd, email) values (%s, %s, %s)", (("python", "123456", "python@gmail.com"), ("java", "456789", "java@gmail.com"), ("php", "123789", "php@gmail.com")))
>>cur.execute("select * from users")
>>lines = cur.fetchall()
>>for line in lines:
print(line)
>>cur.execute("select * from users where id=1")
>>cur.execute("select * from users")
>>cur.fetchone()
>>cur.fetchone()
>>cur.fetchone()
- 游标移动到指定位置
操作存储在内存中的对象时候游标会移动,可以指定游标到某个位置:
>>cur.scroll(2)
>>cur.fetchone()
>>cur.scroll(2, "absolute")
绝对移动的数字不能是负数,相对移动可以是负数
Python
的连接对象的游标方法中提供一个参数,将读取到的数据保存成字典形式:
>>cur = conn.cursor(pymysql.cursors.DictCursor)
>>cur.execute("select * from users")
>>cur.fetchall()
更新
>>cur.execute("update users set username=s% where id=2", ("mypython"))
>>cur.execute("select * from users where id=2")
>>cur.fetchone()