MySQL / Python - Reject queries if the database, table and column are not written within '(accent grave / backtick)

0

I would like to know if there is a way in which I can create restrictions when executing a query. What I would expect is that by having a query like the following:

SELECT * FROM 'database'.'table' WHERE 'column' = 1; -- Notese los ' (acento grave/backtick)

Run without problems.

But when the query is like the following:

SELECT column FROM database.table WHERE other_column = "N/A"; -- Notese la falta de ' (acento grave/backtick) 

Preventing SQL execution.

My connection is made in the following way:

import MySQLdb
from sshtunel import SSHTunerForwarder

class ssh_mysql_exception(Exception):
    pass

class ssh_mysql(object):
    def __init__(self, dsn):
        if 'server_ip' not in dsn or \
           'server_user' not in dsn or \
           'server_pass' not in dsn or \
           'mysql_ip' not in dsn or \
           'mysql_user' not in dsn or \
           'mysql_pass' not in dsn: 
            raise ssh_mysql_exception("Malformed DSN Object")

        self.s_ip = dsn['server_ip']
        self.s_user = dsn['server_user']
        self.s_pass = dsn['server_pass']
        self.mys_ip = dsn['mysql_ip']
        self.mys_user = dsn['mysql_user']
        self.mys_pass = dsn['mysql_pass']

    def query(self, sql):
        with SSHTunnelForwarder(
            (self.s_ip, 22),
            ssh_password=self.s_pass,
            ssh_username=self.s_user,
            remote_bind_address=(self.mys_ip, 3306)
        ) as server:
            driver = MySQLdb.connect(
                host="127.0.0.1",
                port=server.local_bind_port,
                user=self.mys_user,
                passwd=self.mys_pass
            )

            cur = driver.cursor()
            try:
                cur.execute(sql)
                return cur, cur.rowcount
            except Exception as e:
                server.close()
                return str(e)

The class receives an object that has the corresponding keys (server_ip, mysql_ip, etc) for the connection to be successful.

Is there any way to tell the ˝regla˝ or ˝restriction˝ to SQL from the connection or should I find a way to do it with Python?

    
asked by Máxima Alekz 12.03.2018 в 17:19
source

0 answers