How to use the pymysql.escape_string function in PyMySQL

To help you get started, we’ve selected a few PyMySQL examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Keeper-Security / Commander / keepercommander / plugins / mysql / mysql.py View on Github external
with pymysql.connect(host=host, port=int(port), user=user, password=oldpassword) as cursor:
            is_old_version = True
            affected = cursor.execute('select @@version')
            if affected == 1:
                rs = cursor.fetchone()
                version = rs[0]     # type: str
                vc = version.split('.')
                vn = 0
                if len(vc) == 3:
                    for n in vc:
                        vn *= 1000
                        vn += int(n)
                    is_old_version = vn < 5007006

            if is_old_version:
                sql = f'set password for \'{user}\'@\'{user_host}\' = password(\'{pymysql.escape_string(newpassword)}\')'
            else:
                sql = f'alter user \'{user}\'@\'{user_host}\' identified by \'{pymysql.escape_string(newpassword)}\''
            cursor.execute(sql)
            record.password = newpassword
            return True
    except pymysql.err.OperationalError as e:
        logging.error("MySQL Plugin Error: Unable to establish connection: %s", e)
    except pymysql.err.ProgrammingError as e:
        logging.error("MySQL Plugin Syntax Error: %s", e)
    except Exception as e:
        logging.error("MySQL password rotation error: %s", e)

    return False
github ring04h / wyproxy / web / app.py View on Github external
for param in search_str:
        name, value = param.split(':')
        if name not in ['host', 'port', 'status_code','method', 'type', 'content_type', 'scheme', 'extension']:
            return redirect('/')
        params[name] = value
    
    condition = comma = ''
    glue = ' AND '
    for key, value in params.iteritems():
        if ',' in value and key in ['port','status_code','method','type']:
            values = [escape_string(x) for x in value.split(',')]
            condition +=  "{}`{}` in ('{}')".format(comma, key, "', '".join(values))
        elif key in ['host']:
            condition +=  "{}`{}` like '%{}'".format(comma, key, escape_string(value))
        else:
            condition +=  "{}`{}` = '{}'".format(comma, key, escape_string(value))
        comma = glue

    dbconn = connect_db()
    count_sql = 'select count(*) as cnt from capture where {}'.format(condition)
    record_size = int(dbconn.query(count_sql, fetchone=True).get('cnt'))
    
    max_page = record_size/show_cnt + 1
    
    records = dbconn.fetch_rows(
                table='capture',
                condition=condition,
                order=order,
                limit=limits)

    return render_template(
                    'index.html',
github cexll / bili_user_Spider / spider-mysql.py View on Github external
try:
        mid = result.get('mid')
        name = result.get('name')
        sex = result.get('sex')
        regtime = result.get('regtime')
        birthday = result.get('birthday')
        sign = result.get('sign')
        with db.cursor() as cursor:
            sql = "SELECT `mid` FROM `myinfo` WHERE `mid`='%s'" % (mid)
            cursor.execute(sql)
            r = cursor.fetchone()
            if r:
                print('数据库已存在该用户 {}'.format(r))
            else:
                sql = """INSERT INTO `myinfo` (`mid`, `name`, `sex`, `regtime`, `birthday`, `sign`) VALUES ("%s", "%s","%s", "%s","%s", "%s")""" % (
                    mid, name, sex, regtime, birthday, pymysql.escape_string(sign))
                cursor.execute(sql)
                print('{} 用户信息保存到数据库成功'.format(mid))
    finally:
        db.commit()
github ring04h / wyproxy / web / app.py View on Github external
limits = '{},{}'.format((page-1)*show_cnt, show_cnt)
    order = 'id desc'

    search_str = search.split(' ')
    params = {}
    for param in search_str:
        name, value = param.split(':')
        if name not in ['host', 'port', 'status_code','method', 'type', 'content_type', 'scheme', 'extension']:
            return redirect('/')
        params[name] = value
    
    condition = comma = ''
    glue = ' AND '
    for key, value in params.iteritems():
        if ',' in value and key in ['port','status_code','method','type']:
            values = [escape_string(x) for x in value.split(',')]
            condition +=  "{}`{}` in ('{}')".format(comma, key, "', '".join(values))
        elif key in ['host']:
            condition +=  "{}`{}` like '%{}'".format(comma, key, escape_string(value))
        else:
            condition +=  "{}`{}` = '{}'".format(comma, key, escape_string(value))
        comma = glue

    dbconn = connect_db()
    count_sql = 'select count(*) as cnt from capture where {}'.format(condition)
    record_size = int(dbconn.query(count_sql, fetchone=True).get('cnt'))
    
    max_page = record_size/show_cnt + 1
    
    records = dbconn.fetch_rows(
                table='capture',
                condition=condition,
github twindb / proxysql-tools / proxysql_tools / proxysql / proxysql.py View on Github external
def register_backend(self, backend):
        """Register Galera node in ProxySQL

        :param backend: Galera node.
        :type backend: ProxySQLMySQLBackend
        """
        comment = self._get_comment(backend)
        kwargs = {
            'hostgroup_id': int(backend.hostgroup_id),
            'hostname': pymysql.escape_string(backend.hostname),
            'port': int(backend.port),
            'status': backend.status,
            'weight': int(backend.weight),
            'compression': int(backend.compression),
            'max_connections': int(backend.max_connections),
            'max_replication_lag': int(backend.max_replication_lag),
            'use_ssl': int(backend.use_ssl),
            'max_latency_ms': int(backend.max_latency_ms),
            'comment': comment
        }
        query = "REPLACE INTO mysql_servers(" \
                "`hostgroup_id`, `hostname`, `port`, " \
                "`status`, `weight`, `compression`, " \
                "`max_connections`, `max_replication_lag`, `use_ssl`, " \
                "`max_latency_ms`, `comment`) " \
                "VALUES(" \
github twindb / proxysql-tools / proxysql_tools / managers / proxysql_manager.py View on Github external
"""Update the MySQL backend registered with ProxySQL.

        :param backend: The MySQL backend server.
        :type backend: ProxySQLMySQLBackend
        :param proxy_conn: A connection to ProxySQL.
        :type proxy_conn: Connection
        :return: True on success, False otherwise.
        :rtype: bool
        """
        backend.validate()

        col_expressions = []
        val_expressions = []
        for key, val in backend.to_primitive().iteritems():
            col_expressions.append(str(key))
            val_expressions.append("'%s'" % pymysql.escape_string(str(val)))

        with proxy_conn.cursor() as cursor:
            sql = ("REPLACE INTO mysql_servers(%s) VALUES(%s)" %
                   (', '.join(col_expressions), ', '.join(val_expressions)))

            log.debug('Executing query: %s' % sql)

            cursor.execute(sql)
            cursor.execute('SAVE MYSQL SERVERS TO DISK')

            if self.should_reload_runtime:
                cursor.execute('LOAD MYSQL SERVERS TO RUNTIME')

        return True
github Rhilip / Pt-Autoseed / utils / database.py View on Github external
def get_data_clone_id(self, key, site) -> None or int:
        clone_id = None

        key = pymysql.escape_string(re.sub(r"[_\-. ]", "%", key))
        sql = "SELECT `{site}` FROM `info_list` WHERE `search_name` LIKE '{key}'".format(site=site, key=key)
        try:  # Get clone id info from database
            clone_id = int(self.exec(sql=sql)[0])
        except TypeError:  # The database doesn't have the search data, Return dict only with raw key.
            logging.warning(
                "No record for key: \"{key}\" in \"{site}\". Or may set as `None`".format(key=key, site=site)
            )

        return clone_id
github kong36088 / ZhihuSpider / get_user.py View on Github external
company = user_info['employments'][0]['company']['name'] if len(user_info['employments']) > 0 and 'company' in user_info['employments'][0]  else ''
            school = user_info['educations'][0]['school']['name'] if len(user_info['educations']) > 0 and 'school' in user_info['educations'][0]  else ''
            major = user_info['educations'][0]['major']['name'] if len(user_info['educations']) > 0 and 'major' in user_info['educations'][0] else ''
            job = user_info['employments'][0]['job']['name'] if len(user_info['employments']) > 0 and 'job' in user_info['employments'][0] else ''
            location = user_info['locations'][0]['name'] if len(user_info['locations']) > 0 else ''
            description = user_info['description'] if 'description' in user_info else ''
            ask_num = int(user_info['question_count'])
            answer_num = int(user_info['answer_count'])
            article_num = int(user_info['articles_count'])
            collect_num = int(user_info['favorite_count'])
            public_edit_num = int(user_info['logs_count'])

            replace_data = \
                (pymysql.escape_string(name_url), nickname, self_domain, user_type,
                 gender, follower_num, following_num, agree_num, appreciate_num, star_num, share_num, browse_num,
                 trade, company, school, major, job, location, pymysql.escape_string(description),
                 ask_num, answer_num, article_num, collect_num, public_edit_num)

            replace_sql = '''REPLACE INTO
                          user(url,nickname,self_domain,user_type,
                          gender, follower,following,agree_num,appreciate_num,star_num,share_num,browse_num,
                          trade,company,school,major,job,location,description,
                          ask_num,answer_num,article_num,collect_num,public_edit_num)
                          VALUES(%s,%s,%s,%s,
                          %s,%s,%s,%s,%s,%s,%s,%s,
                          %s,%s,%s,%s,%s,%s,%s,
                          %s,%s,%s,%s,%s)'''

            try:
                print("获取到数据:")
                print(replace_data)
                self.db_cursor.execute(replace_sql, replace_data)