json
什么是json
JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAScript (w3c制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
JSON支持数据格式
- 对象(字典)。使用花括号。
- 数组(列表)。使用方括号。
- 整形、浮点型、布尔类型还有null类型。
- 字符串类型(字符串必须要用双引号,不能用单引号)。
多个数据之间使用逗号分开。
注意:json本质上就是一个字符串。
字典和列表转JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import json
books = [ { 'title': '钢铁是怎样练成的', 'price': 9.8 }, { 'title': '红楼梦', 'price': 9.9 } ]
json_str = json.dumps(books,ensure_ascii=False) print(json_str)
|
因为json
在dump
的时候,只能存放ascii
的字符,因此会将中文进行转义,这时候我们可以使用ensure_ascii=False
关闭这个特性。
在Python
中。只有基本数据类型才能转换成JSON
格式的字符串。也即:int
、float
、str
、list
、dict
、tuple
。
将json
数据直接dump
到文件中
json
模块中除了dumps
函数,还有一个dump
函数,这个函数可以传入一个文件指针,直接将字符串dump
到文件中。示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12
| books = [ { 'title': '钢铁是怎样练成的', 'price': 9.8 }, { 'title': '红楼梦', 'price': 9.9 } ] with open('a.json','w') as fp: json.dump(books,fp)
|
将一个json字符串load成Python对象
1 2 3 4 5
| json_str = '[{"title": "钢铁是怎样练成的", "price": 9.8}, {"title": "红楼梦", "price": 9.9}]' books = json.loads(json_str,encoding='utf-8') print(type(books)) print(books)
|
直接从文件中读取json
1 2 3 4 5
| import json with open('a.json','r',encoding='utf-8') as fp: json_str = json.load(fp) print(json_str)
|
MySQL数据库操作
数据库连接
数据库连接之前。首先先确认以下工作完成,这里我们以一个pymysql_test
数据库.以下将介绍连接mysql
的示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import pymysql
db = pymysql.connect( host="127.0.0.1", user='root', password='root', database='pymysql_test', port=3306 ) cursor = db.cursor() cursor.execute("select 1") data = cursor.fetchone() print(data) db.close()
|
插入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import pymysql
db = pymysql.connect( host="127.0.0.1", user='root', password='root', database='pymysql_test', port=3306 ) cursor = db.cursor() sql = """ insert into user( id,username,gender,age,password ) values(null,'abc',1,18,'111111'); """ cursor.execute(sql) db.commit() db.close()
|
如果在数据还不能保证的情况下,可以使用以下方式来插入数据:
1 2 3 4 5 6 7 8
| sql = """ insert into user( id,username,gender,age,password ) values(null,%s,%s,%s,%s); # 都是%s,无论mysql表里是什么类型,pymysql处理 """
cursor.execute(sql,('spider',1,20,'222222'))
|
查找数据
使用pymysql
查询数据。可以使用fetch*
方法。
fetchone()
:这个方法每次之获取一条数据。
fetchall()
:这个方法接收全部的返回结果。
fetchmany(size)
:可以获取指定条数的数据。
示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| cursor = db.cursor()
sql = """ select * from user """
cursor.execute(sql) while True: result = cursor.fetchone() if not result: break print(result) db.close()
|
或者是直接使用fetchall
,一次性可以把所有满足条件的数据都取出来:
1 2 3 4 5 6 7 8 9 10 11
| cursor = db.cursor()
sql = """ select * from user """
cursor.execute(sql) results = cursor.fetchall() for result in results: print(result) db.close()
|
或者是使用fetchmany
,指定获取多少条数据:
1 2 3 4 5 6 7 8 9 10 11
| cursor = db.cursor()
sql = """ select * from user """
cursor.execute(sql) results = cursor.fetchmany(1) for result in results: print(result) db.close()
|
删除数据
1 2 3 4 5 6 7 8 9 10
| cursor = db.cursor()
sql = """ delete from user where id=1 """
cursor.execute(sql) db.commit() db.close()
|
更新数据
1 2 3 4 5 6 7 8 9 10 11
| conn = pymysql.connect(host='localhost',user='root',password='root',database='pymysql_demo',port=3306) cursor = conn.cursor()
sql = """ update user set username='aaa' where id=1 """
cursor.execute(sql)
conn.commit() conn.close()
|
MongoDB
概念介绍
SQL术语/概念 |
MongoDB术语/概念 |
解释/说明 |
database |
database |
数据库 |
table |
collection |
数据库表/集合 |
row |
document |
数据记录行/文档 |
column |
field |
数据字段/域 |
index |
index |
索引 |
joins |
joins |
表连接,MongoDB不支持 |
primary key |
primary key |
主键,MongoDB自动将_id字段设置为主键 |
MongoDB三元素
数据库、集合、文档
- 文档(document):就是关系型数据库中的一行。文档是一个对象,由键值对构成,是
json
的扩展形式。
1
| {'name':'abc', 'gender': '1'}
|
- 集合(collection):就是关系型数据库中的表。可以存储多个文档,结构可以不固定。如可以存储如下文档在一个集合中:
1 2 3
| {"name":"abc","gender":"1"} {"name":"xxx","age":18} {"title":"yyy","price":20.9}
|
MongoDB基本操作命令
- db:查看当前的数据库
- show dbs:查看所有的数据库
- use 数据库名:切换数据库。如果数据库不存在,则创建一个。(创建完成后需要插入数据库才算创建成功)
- db.dropDatabase():删除当前指向的数据库
- db.集合名.insert(value):添加数据到指定的集合中
- db.集合名.find():从指定的集合中查找数据
python操作MongoDB
安装pymongo
连接MongoDB
1 2 3 4 5 6 7 8 9 10 11 12 13
| import pymongo
client = pymongo.MongoClient('127.0.0.1', port=27017)
db = client.zhihu
collection = db.qa
collection.insert_one({ "username": "abc", "password": "hello" })
|
数据类型
类型 |
说明 |
Object ID |
文档ID |
String |
字符串,最常用,必须是有效的UTF-8 |
Boolean |
存储一个布尔值,True和False |
Integer |
整数可以是32位或64位,取决于服务器 |
Double |
存储浮点值 |
Arrays |
数组或列表,多个值存储到一个键 |
Object |
用于嵌入式的文档,即一个值为一个文档 |
Null |
存储Null值 |
Timestamp |
时间戳,表示从1970-1-1 到现在的总秒数 |
Date |
存储当前日期或时间的UNIX时间格式 |
操作MongoDB
insert_one
:加入一条文档数据到集合中
1 2 3 4
| collection.insert_one({ "username":"abc", "password":"hello" })
|
insert_many
:加入多条文档数据到集合中
1 2 3 4 5 6 7 8 9 10
| collection.insert_many({ { "username": "abc", "password": "11111" }, { "username": "bbbb", "password": "2222" } })
|
find_one
:查找一条文档对象
1 2 3 4 5 6
| result = collection.find_one() print(result)
result = collection.find_one({"username": "abc"}) print(result)
|
update_one
:更新一条文档对象
1
| collection.update_one({"username":"abc"},{"$set":{"username":"aaa"}})
|
update_many
:更新多条文档对象
1
| collection.update_many({"username":"abc"},{"$set":{"username":"aaa"}})
|
delete_one
:删除一条文档对象
1
| collection.delete_one({"username":"abc"})
|
delete_many
:删除多条文档对象
1
| collection.delete_one({"username":"abc"})
|