当前位置: 移动技术网 > IT编程>脚本编程>Python > python中连接三大主流数据库mysql,mongodb和redis的操作教程

python中连接三大主流数据库mysql,mongodb和redis的操作教程

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

牛耳大黄,443399小游戏,非诚勿扰白俄罗斯

1.python中mysql的连接

import pymysql

connection=pymysql.connect('localhost','root','password','database')    #创建连接对象
cursor=connection.cursor()                                              #创建游标对象
sql=''
cursor.execute(sql)                                                     #执行sql语句
emp=cursor.fetchone()                                                   #返回执行之后得到的第一条结果
print(emp)
cursor.close()                                                          #关闭游标对象
connection.close()                                                      #关闭数据库连接

2.python中mongodb数据库的连接

import pymongo
client=pymongo.mongoclient(host='localhost',port=27107)           #创建连接数据库的对象
db=client.test()                                                  #指定数据库
collection=db.students                                            #声明一个collection对象
student1={                                                        #插入数据
    'id':'20170101',
    'name':'coolcooljob',
    'gender':'boy'
}
student2={                                                        #插入多条数据
    'id':'20170102',
    'name':'jack',
    'gender':'boy'
}
result=collection.insert_many([student1,student2])
print(result)
print(result.inserted_id)
result1=collection.find_one({'name':'jack'})
print(type(result1))
print(result1)

3.python中redis数据库的连接(两种)

第一种:直接使用strictredis

from redis import strictredis
redis=strictredis(host='localhost',port=6379,db=0,password='password')    #创建连接对象
redis.set('name','coolcooljob')                                           #插入数据
print(redis.get('name'))    

第二种:利用connectionpool连接

from redis import strictredis,connectionpool
pool=connectionpool(host='localhost',port=6379,db=0,password='password')
redis=strictredis(connection_pool=pool)                                   #另外一种创建连接对象的方法

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网