【学习心得】Python操作数据库口诀

(一)Python操作MySQL

  • Python操作MySQL有两个常用库
  1. pip install mysql-connector
  2. pip install pymysql
  • 操作MySQL的5个步骤
  1. 创建连接对象;
  2. 生成游标指针;
  3. 编写SQL语句;
  4. 执行SQL语句;
  5. 提交事务,关闭连接。
"""
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

  • Python操作MongoDB的常用库
  1. pip install pymongo
  • 操作MongoDB的4个步骤
  1. 连接服务器;
  2. 连接数据库;
  3. 连接集合;
  4. 操作数据。
"""
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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值