(一)Python操作MySQL
- pip install mysql-connector
- pip install pymysql
- 创建连接对象;
- 生成游标指针;
- 编写SQL语句;
- 执行SQL语句;
- 提交事务,关闭连接。
"""
python操作 MYSQL 数据库的5个步骤:
1、创建连接对象
2、生成游标指针
3、编写SQL语句
4、执行SQL语句
5、提交事务,关闭连接
"""
# 导入pymysql库
import pymysql
# 创建连接对象
db = pymysql.connect(host='localhost',
port=3306, # 这里传入的端口号是int类型
user='root',
# password='', # 这里没有密码就不传
database='test')
# 生成游标指针
test_cursor = db.cursor()
# 编写SQL语句
SQL = 'select * from student;'
# 执行SQL语句
test_cursor.execute(SQL)
# 输入查询结果fetchall()获取全部查询结果,fetchone()获得一条查询结果
result = test_cursor.fetchall()
for stu in result:
print('id =', stu[0], end='\t')
print('name =', stu[1], end='\t')
print('gender =', stu[2], end='\t')
print('score =', stu[3], end='\t')
print()
# 关闭连接,因为没有改变数据所以不需要提交事务
db.close()
(二)Python操作MongoDB
- pip install pymongo
- 连接服务器;
- 连接数据库;
- 连接集合;
- 操作数据。
"""
python 控制 MongoDB 的4个步骤:
1、连接服务器
2、连接数据库
3、连接集合
4、操作数据(增删改查)
"""
# 导入 pymongo
import pymongo
# 连接 MongoDB
client = pymongo.MongoClient(host='localhost', port=27017)
# 连接 数据库
db = client.school
# 连接 集合
collection = db.student
# 操作数据
# 插入 insert_one() insert_many()
collection.insert_one({'name': 'shankou', 'gender': 'male'})
lis = [
{'name': 'zikai', 'age': 18},
{'name': 'cuixin', 'age': 19, 'gender': 'male'}
]
collection.insert_many(lis)
# 删除 delete_one() delete_many()
collection.delete_one({'name': 'shankou'})
collection.delete_many({'name': 'zikai'})
# 修改 update_one() update_many()
# 查询 find() find_one()
result = collection.find()
print(result) # 返回一个可迭代的cursor
for stu in result:
print(stu)
print()
result_one = collection.find_one()
print(result_one)