Python与数据库的交互

对于关系型数据库的访问,Python社区已经指定了一个标准,称为Python Database API SepcificationV2.0.MySQL、Qracle等特定数据库模块遵从这一规范,而且可添加更多特性
高级数据库API定义了一组用于连接数据库服务器、执行SQL语句并获得结果的函数和对象,其中有两个主要的对象:一个是用于管理数据库连接的Connection对象,另一个是用于执行查询的Cursor对象。

Python DB-API使用流程:

  • 引入 API 模块。
  • 获取与数据库的连接。
  • 执行SQL语句和存储过程。
  • 关闭数据库连接。

现在我们开始来学习一下怎么连接操作mysql。首先我们需要导入pymysql的模块,import pymysql。然后调用pymysql.connect()连接数据库。调用connect发回的游标connection.cursor(),执行查询语句。接下来我们需要调用cursor.execute()来执行sql语句,connection.commit(),最后调用connection.close()方法关闭数据库连接。

一、MySQL与Python的交互

在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装

$ pip3 install PyMySQL

本地连接

import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
 
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
# 关闭数据库连接
db.close()

虚拟机连接

第一种

import pymysql
db_config = {
    'user':'root',
    'password':'qwe123',
    'db':'crm',
    'charset':'utf8'
}
conn = pymysql.connect(**db_config)
cur = conn.cursor()
cur.execute('select * from teacher_student')
print(cur.fetchall())
cur.close()
conn.close()

第二种 with方法

import pymysql
my_config = {
    'user': 'root',
    'password':'qwe123',
    'db':'crm',
    'charset':'utf8'
}

with pymysql.connect(**my_config) as cur:
    cur.execute('select * from teacher_student')
    row = cur.fetchone()
    while row:
        print('ROW',row)
        row = cur.fetchone()

二、mongo与Python的交互

import pymongo
collection = pymongo.MongoClient()
db = collection['my_mongo'] 
my_col = db['student']
result = my_col.insert_one({'name':'毛利'},{'age':18})

在这里插入图片描述

三、redis与Python的交互

import redis
conn = redis.StrictRedis() #就是一个StrictRedis()
result = conn.get('name')
print(result)

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44510615/article/details/88652961