zoukankan      html  css  js  c++  java
  • sql参数化

    查询

    sql = "select * from users where username=%s and password=%s"
    cursor.execute(sql,user,pwd)

    插入

    sql = "INSERT INTO USER(NAME,PASSWORD) VALUES(%s,%s)"
     
    cur.execute(sql, ('test', '888888'))

    更新

    cs1.execute('update student set name="%s" where name ="%s"',["lv","da"])

    删除

    cs1.execute('delete from student  where name =%s', ["haha"])

    封装

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @File    : mysql_handle.py
    # 还需要再修改,没有考虑id=2 or id =3这种情况
    
    import pymysql
    import database
    
    
    class MysqlHandle(object):
        def __init__(self, source, which_db):
            try:
                self.conn = pymysql.Connect(
                    host=database.CONNECTIONS[source]['HOST'],
                    port=database.CONNECTIONS[source]['PORT'],
                    db=database.CONNECTIONS[source]['DB'][which_db],
                    user=database.CONNECTIONS[source]['USER'],
                    passwd=database.CONNECTIONS[source]['PASSWD'],
                    charset=database.CONNECTIONS[source]['CHARSET'],
                )
                self.cur = self.conn.cursor()
            except Exception as e:
                print(e)
    
        def select_handle(self, table_name, *query_values, **conditions):     # 知识点
            row = ""
            if query_values == ():
                row = "* "
            else:
                for query_value in query_values:
                    row += query_value + ','
            try:
                if conditions == {}:
                    sql = "select " + row[:-1] + " from " + table_name
                    self.cur.execute(sql)
                    result = self.cur.fetchall()
                else:
                    columns = ""
                    values = []
                    for key in conditions:
                        columns += key + "= %s and "
                        values.append(conditions[key])
                    sql = "select " + row[:-1] + " from " + table_name + " where " + columns[:-4]
                    self.cur.execute(sql, values)
                    result = self.cur.fetchone()
                # 提交事务
                self.conn.commit()
            except:
                result = None
            return result
    
        def insert_handle(self, table_name, data):
            if isinstance(data, dict):
                columns = ""
                values = []
                variable = ""
                for key in data:
                    columns += key + ","
                    values.append(data[key])
                    variable += "%s,"
                sql = 'INSERT INTO ' + table_name + '(' + columns[:-1] + ') ' + 'VALUES' + '(' + variable[:-1] + ')'
                try:
                    self.cur.execute(sql, values)
                    self.conn.commit()
                except:
                    print("插入数据失败")
                return
            else:
                print('不是字典')
    
        def update_handle(self, table_name, data, **conditions):
            # update student set name="haha",age="14" where name ="hehe"
            if isinstance(data, dict):
                data_variable = ""
                data_values = []
                for key in data:
                    data_variable += key + '="%s",'
                    data_values.append(data[key])
                try:
                    if conditions == {}:
                        sql = "update " + table_name + " set " + data_variable[:-1]
                        self.cur.execute(sql, data_values)
                    else:
                        conditions_variable = ""
                        conditions_values = []
                        for key in conditions:
                            conditions_variable += key + "= %s and "
                            conditions_values.append(conditions[key])
                        sql = "update " + table_name + " set " + data_variable[:-1] + " where " + conditions_variable[:-4]
                        self.cur.execute(sql, data_values + conditions_values)
                    self.conn.commit()
                except:
                    print("更新失败")
    
        def delete_handle(self, table_name, **conditions):
            #delete from student  where name ="haha"
            # print(conditions)
            try:
                if conditions == {}:
                    sql = "delete from "+table_name
                    self.cur.execute(sql)
                else:
                    conditions_variable = ""
                    conditions_values = []
                    for key in conditions:
                        conditions_variable += key + "=%s and "
                        conditions_values.append(conditions[key])
                    sql = "delete from " + table_name + " where "+conditions_variable[:-4]
                    self.cur.execute(sql, conditions_values)
                # 提交事务
                self.conn.commit()
            except:
                print("删除失败")
    
        def __del__(self):
            # 关闭游标
            self.cur.close()
            # 关闭链接
            self.conn.close()
    
    
    if __name__ == '__main__':
        mh = MysqlHandle('local', 0)
        print(mh.select_handle('users'))
        # user_dict = {
        #     'user_id': '10',
        #     'first_name': '23',
        #     'last_name': '3',
        #     'user': '3',
        #     'password': '3',
        #     'avatar': '3',
        #     'last_login': '2019-09-10 16:37:32',
        # }
        # user_dict2 = {
        #     'avatar': '3333',
        # }
        # mh.insert_test('users', user_dict)
        # mh.update_test('users', user_dict2, user_id=8)
        # mh.delete_test('auth_group', name=5)
     
  • 相关阅读:
    C 和 C++ 的标准库分别有自己的 locale 操作方法,C 标准库的 locale 设定函数是 setlocale(),而 C++ 标准库有 locale 类和流对象的 imbue() 方法(gcc使用zh_CN.GBK,或者zh_CN.UTF-8,VC++使用Chinese_People's Republic of China.936或者65001.)
    QCache 缓存(模板类,类似于map,逻辑意义上的缓存,方便管理,和CPU缓存无关。自动获得被插入对象的所有权,超过一定数量就会抛弃某些值)
    QBuffer简单操作(被看做一个标准的可随机访问的文件,支持信号)
    Qt里的原子操作QAtomicInteger
    进程、线程、协程、例程、过程
    net Core 2.2
    如何看源码
    code review规则
    NET Core中使用Dapper操作Oracle存储过程
    实现一个Promise
  • 原文地址:https://www.cnblogs.com/lvchengda/p/12617887.html
Copyright © 2011-2022 走看看