当前位置: 移动技术网 > IT编程>脚本编程>Python > MySQL、mongodb、Redis与python的交互

MySQL、mongodb、Redis与python的交互

2018年02月23日  | 移动技术网IT编程  | 我要评论

数据库与python的交互

1.MySQL与python的交互

1 .建立链接:

try:
    from mysql import *  
    con = connect(
        host = "localhost",
        port = 3306,
        database = 'df',
        user = 'root',
        password = 'mysql',
        charset = 'utf-8'
        )  

2 .连接对象:

    #获得cursor对象
    cs1 = con.cursor()
    #执行insert语句,students是表明
    count = cs1.execute('insert into students(name) values("天明")')
    #更新数据
    count = cs1.execute('updata students set name="少羽" where id=5 ')
    #查询操作 
    count=cs1.execute('select id,name from students')
    #获取查询的一条结果
    result = cs1.fetchone()
    # 获取查询的所有的结果
    results = cs1.fetchall()

    #关闭对象
    cs1.cloes()
    #提交,只有删除和增加的时候才有commit操作
    con.commit()
    except Exception as e:
        print(e)
    finnally:
        #最后关闭con,为避免数据写入的时候出错,可以放在try里避免
        con.close()

2.mongodb与python的交互

1.建立链接

from pymongo import MongoClient
client = MongoClient(host='localhost', port=27017)

2.选择数据库和集合

# 选择python这个数据库
database = client.python
# 选择py这个集合
collection = database.py
#向数据库中插入一条数据
collection.isnert_one({"key":"value"})
#插入多条数据
collection.inser_many([{"key1":"value1"},{"key2":"value2"},...])
# 查询多条数据
result = collection.find({"key":"value"})   

Redis和phton的交互

1.建立链接

from redis import *
cient = StrictRedis()
#添加,更新
result=client.set('py1','gj')
#获取
result = client.get('py1')
#删除
result = client.delete('py1')
#获取键
result = client.keys()

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网