[Mysql] Python은 Mysql에 연결하여 추가, 삭제, 수정 및 확인

1. Python이 Mysql에 연결

일상적인 코딩 테스트 과정에서 추가, 삭제, 수정, 쿼리 작업을 위해 데이터베이스에 연결해야 하는 경우가 많은데, 다음으로 패키징 작업을 수행하는 방법을 소개합니다.

1.1 Python은 pymysql 모듈을 가져옵니다.

pip install PyMySQL

여기에 버전 1.0.2를 설치했습니다.
여기에 이미지 설명 삽입

1.2, mysql 작업 연결

1.2.1 먼저 모듈을 가져옵니다.

import pymysql as my
import time
from Demaxiya.openpay.untils.untils_api import read_data_yaml

1.2.2 데이터베이스에 연결:

class Mysql(object):

    def __init__(self, db="risk"):
        # 数据库连接重试功能和连接超时功能的DB连接
        self._max_retries_count = 2  # 设置最大重试次数
        self._conn_retries_count = 0  # 初始重试次数
        self._conn_timeout = 100  # 连接超时时间为10秒
        # mysql数据库连接
        if db == 'risk':
            self.db_host = read_data_yaml()['test']['mysql']['risk']['host']
            self.username = read_data_yaml()['test']['mysql']['risk']['user']
            self.pw = read_data_yaml()['test']['mysql']['risk']['password']
            self.dbname = read_data_yaml()['test']['mysql']['risk']['name']
        if db == 'afi':
            self.db_host = read_data_yaml()['test']['mysql']['afi']['host']
            self.username = read_data_yaml()['test']['mysql']['afi']['user']
            self.pw = read_data_yaml()['test']['mysql']['afi']['password']
            self.dbname = read_data_yaml()['test']['mysql']['afi']['name']
        if db == 'aku':
            self.db_host = read_data_yaml()['test']['mysql']['aku']['host']
            self.username = read_data_yaml()['test']['mysql']['aku']['user']
            self.pw = read_data_yaml()['test']['mysql']['aku']['password']
            self.dbname = read_data_yaml()['test']['mysql']['aku']['name']
        while self._conn_retries_count <= self._max_retries_count:
            try:
                self.db = my.connect(
                    host=self.db_host,
                    user=self.username,
                    password=self.pw,
                    db=self.dbname,
                    charset='utf8',
                    connect_timeout=self._conn_timeout)
                # cursor = self.db.cursor()#创建游标
                self.cursor = self.db.cursor(cursor=my.cursors.DictCursor)  # 查询结果以字典形式返回
                print("mysql连接success")
                break
            except:
                print("mysql连接false")
                self._conn_retries_count += 1
            time.sleep(2)
            continue

1.2.3 새로운 삽입 작업:

 def inserDB(self, sql):
        # 插入数据库操作
        try:
            # 执行sql
            self.cursor.execute(sql)
            self.db.commit()
            print("数据库插入操作-成功")
        except Exception as e:
            # 异常捕获
            raise e
            # 发生错误时回滚
            self.db.rollback()

1.2.4 업데이트 업데이트 작업:

    def updateDB(self, sql):
        # ''' 更新数据库操作 '''
        try:
            # 执行sql
            self.cursor.execute(sql)
            self.db.commit()
            print("更新数据库操作-成功")
        except Exception as e:
            # 异常捕获
            raise e
            # 发生错误时回滚
            self.db.rollback()

1.2.5 쿼리 선택 문:

    def selectDB(self, sql):
        # ''' 数据库查询 '''
        while self._conn_retries_count <= self._max_retries_count:
            try:
                self.cursor.execute(sql)  # 返回 查询数据 条数 可以根据 返回值 判定处理结果
                data = self.cursor.fetchall()  # 返回查询记录列表
                if data == ():
                    return "结果为空了啊,请查看sql正确"
                    break
                else:
                    return [item[key] for item in data for key in item]
                    # print([item[key] for item in data for key in item])
                    break
            except Exception as e:
                raise e
                continue
        self.cursor.close()
        self.db.close()

1.2.6, SQL 결과 실행

if __name__ == "__main__":
    test = 1
    sql = "select uid from `test`.`t_1` where test='{}';".format(test)
    print(sql)
    test = Mysql('test').selectDB(sql=sql)
    此时是以列表结果形式返回的:所以要test[0]这样就可以获得查询结果了

추천

출처blog.csdn.net/weixin_52358204/article/details/125209459