Search code examples
pythonmysqlstringcursor

MySQL python: Cursor returns the variable name


I saw before if someone ask the same but i didn't see a similar question.

def get_session(Var = '', Key=''):
    conn = connection()
    cursor = conn.cursor()
    print "Var: "+Var
    cursor.execute("Select %(var)s FROM users WHERE sessions = %(key)s",{'var':Var,'key':Key})
    if(cursor.rowcount == 1):
        name = cursor.fetchone()
        print name
        return name

The output is like:

get_session(Var = 'NAME', Key='asdf123')

Var:NAME

('NAME',)

+----+----------+----------+---------------------------+
| ID | NAME     | PASS     |  sessions                 |
+----+----------+----------+---------------------------+
|  1 | Potato   | test     |  asdf123                  |
|  2 | asdf123  | test2    |  asdasd                   |
+----+----------+----------+---------------------------+

The correct output must be:

get_session(Var = 'NAME', Key='asdf123')

Var:NAME

('Potato',)

or

get_session(Var = 'PASS', Key='asdf123')

Var:PASS

('test',)

I supposed that the main problem is that mysql detects the name with quotes but i don't know how to fix it.


Solution

  • The problem was the quotes that sql put in automatically

    def get_session(Var = '', Key=''):
        conn = connection()
        cursor = conn.cursor()
        sql = "Select "+ Var+" FROM users WHERE sessions = %(key)s"
        print "Var: "+Var
        cursor.execute(sql,{'key':Key})
        print str(cursor.rowcount)
        if(cursor.rowcount == 1):
            name = cursor.fetchone()
            print name
            return name
        else:
            return None
        cursor.close()
        conn.close()
    

    Thanks to all for responding.