zoukankan      html  css  js  c++  java
  • Python-操作数据库之pymysql

    import pymysql
    import yaml
    
    '''
    mysql.connector基本应用
    数据库:存储项目数据
    验证数据  -->代码取数据库数据与实际结果进行比对
    步骤:
        1、连接数据库
        2、创建游标实例
        3、调用游标实例的excute(sql)  excute(sql,sql_value,bool)sql语句
        
        sql语句  -->读取yaml数据
        执行语句  --> excute
        
    注意: 防止SQL注入,where/delete/update/insert等涉及到查询的值都使用占位符%s,mysql.connector/pymysql模块会自动转义    
    '''
    class MySQL:
        def __init__(self,name):
            self.db = pymysql.connect(
                host="localhost",
                database=name,
                user="root",
                password="admin123"
            )
            # 获取游标实例
            self.cursor = self.db.cursor()
            print(self.cursor)
    
        def excute_sql_val(self,sql,sql_val=None):
            self.cursor.execute(sql,sql_val)
            for data in self.cursor:
                return data
    
        def update_sql_val(self,sql,sql_val=None):
            self.cursor.execute(sql,sql_val)
            self.db.commit()
            print(self.cursor.rowcount, "db have changed")
    
        #需要一次性插入多行数据
        def excute_many(self,sql,sql_val):
            self.cursor.executemany(sql,sql_val)
            self.db.commit()
            print(self.cursor.rowcount, "many sqls have excuted")
    
        #获取所有行
        def fetchall(self,sql,sql_val=None):
            self.cursor.execute(sql,sql_val)
            res = self.cursor.fetchall()
            for data in res:
                return data
    
        #只返回结果的第一行
        def fetchone(self,sql,sql_val=None):
            self.cursor.execute(sql,sql_val)
            res = self.cursor.fetchone()
            return res
    
    
    
    
    mysql = MySQL(name="mydatabase")
    with open(file="sql_data.yaml",mode="r",encoding="UTF-8") as file:
        data = yaml.load(stream=file,Loader=yaml.FullLoader)
    print(type(data))
    print(data)
    for k,v in data.items():
        mysql.excute_sql_val(sql=v)
    三十六般武艺,七十二般变化,修练出个人品牌并发出光芒
  • 相关阅读:
    SerializationUtility
    ExtendHelper
    AutoTransformHandler
    Parameter Config
    Tools Function
    谈谈对C#中反射的一些理解和认识(上)
    WPF程序中App.Config文件的读与写
    WPF实现Windows资源管理器(附源码)
    安装VC++2015运行库时出现0x80240037错误
    对C#调用C++的dll的一点思考
  • 原文地址:https://www.cnblogs.com/deeptester-vv/p/15136573.html
Copyright © 2011-2022 走看看