美文网首页
Python中连接数据库的方法(Mysql、Mongodb、Re

Python中连接数据库的方法(Mysql、Mongodb、Re

作者: 65f0ee1aa08d | 来源:发表于2018-12-17 10:52 被阅读0次

基本的操作,时常会用到,记录一下

一、Mysql

# coding=utf-8
from MySQLdb import *  # pymysql类似

# 连接数据库
conn = connect(host='localhost',port=3306,user='root',passwd='mysql',db='python3',charset='utf8')
cursor1 = conn.cursor()  # 一个游标对象

# 接下来是实际操作部分,在sql中写正常的sql语句即可
sql = 'insert into student(name) values("郭小二")'
# 如果sql里面是一个查询语句的话,则用fetch获取所有记录
# 获取所有记录列表 一个元组组成的元组((),(),())
# results = cursor1.fetchall()
cursor1.execute(sql)  # 执行
conn.commit()

# 关闭连接
cursor1.close()
conn.close()

二、Mongodb

# coding=utf-8
from pymongo import *

# 获得客户端,建立连接
client = MongoClient('mongodb://localhost:27017')
# 有安全认证的
# client = MongoClient('mongodb://用户名:密码@localhost:27017/数据库名称')

db = client.py3  # 连接py3数据库,没有则自动创建
stu = db.stu  # 使用stu集合,没有则自动创建

# 增加,返回插入文档的id
# s1 = stu.insert({'name':'张三丰'})
# print(s1)

# 修改,前面的是条件
# stu.update_one({'name':'张三丰'}, {'$set':{'name':'abc'}})

# 删除
# stu.delete_one({'name':'abc'})

# 查询
cursor = stu.find({'age':{'$gt':20}}).sort('_id', -1)      # .skip(1).limit(1)
for s in cursor:
    print(s['name'])

三、Redis

# coding=utf-8
from redis import *

# r = StrictRedis(host='localhost', port=6379)

# 写
# pipe = r.pipeline()
# pipe.set('py10', 'hello1')
# pipe.set('py11', 'world')
# pipe.execute()

# 读
# temp = r.get('py10')
# print(temp)

相关文章

网友评论

      本文标题:Python中连接数据库的方法(Mysql、Mongodb、Re

      本文链接:https://www.haomeiwen.com/subject/rilqkqtx.html