003 爬虫持久化的三个不同数据库的python代码

时间:2023-03-09 04:05:16
003  爬虫持久化的三个不同数据库的python代码

MongoDB

import pymongo

# 1、连接MongoDB服务
mongo_py = pymongo.MongoClient()
print(mongo_py) # 2、库和表的名字;有时间会自动建库建表
# 数据库
db = mongo_py['test2'] # 表、集合
collection = db['stu']
# 或
# collection = mongo_py.test2.stu one = {'name': '张三', 'age': 15}
two_many = [{'name': '张四', 'age': 25},
{'name': '张五', 'age': 12},
{'name': '张六', 'age': 17}] # 3、插入数据
collection.insert(one)
collection.insert_many(two_many) # 4、删除数据
collection.delete_many({'name': "张四"}) # 5、更改数据
collection.update({'name': '张三'}, {"name": '小张'}) # 6、查询数据
result = collection.find({'age': 17})
print(result) # 关闭数据库
mongo_py.close()

MongoDB的增删改查

redis

import redis
client = redis.Redis()
# print(client)
# 2、设置key
key = 'pyone'
key2 = 'py4'
# 3、string增加
result = client.set(key, '')
result = client.set(key2, '')
print(result)
# 删除
result = client.delete(key)
# 修改
result = client.set(key2, '')
# 查看
result = client.get(key2)
print(str(result))

redis的代码

MySQL

import pymysql

# 1、 连接数据库
conn = pymysql.Connect(
host='127.0.0.1',
db='grade',
user='root',
password=''
)
print(conn)
# 打开游标对象
cur = conn.cursor()
# 2、增加数据
insert_sub = 'insert into student values("2000000", "新增", 1, "理学院", " ")'
cur.execute(insert_sub)
# 提交事务
conn.commit()
# 3、删除数据
delete_sub = 'delete from student where sid="2000000"'
cur.execute(delete_sub)
conn.commit() # 需要提交
# 4、修改数据库
update_sub = 'update student set name="新增1" where sid="2000000"'
cur.execute(update_sub)
conn.commit()
# 5、查看数据
show_data = 'select * from student where name="新增1"'
cur.execute(show_data)
data = cur.fetchall()
print(data) # 关闭数据 cur.close()
conn.close()

mysql代码