Alex
Alex

Reputation: 151

Python - where's the error in my MySQL query?

I'm working with PyMySQL and Python.

 sql = "INSERT INTO accounts(date_string, d_day, d_month, d_year, trans_type, descriptor, inputs, outputs, balance, owner) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', AES_ENCRYPT('%s', 'example_key_str')"
cur.execute(sql % (date, d_day, d_month, d_year, ttype, desc, money_in, money_out, bal, owner))

This throws a vague syntax error, and I have no idea how to fix it. The evaluated query is:

INSERT INTO accounts(date_string, d_day, d_month, d_year, trans_type, descriptor, inputs, outputs, balance, owner) VALUES ('12 Feb 2012', '12', 'Feb', '2012', 'CHQ', 'CHQ 54', '7143.78', '0.00', '10853.96', AES_ENCRYPT('[email protected]', 'example_key_str')

The MySQL error is:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Any help would be much appreciated. Thanks in advance.

Upvotes: 1

Views: 55

Answers (1)

alecxe
alecxe

Reputation: 473793

There is no closing parenthesis:

INSERT INTO 
    accounts
    (date_string, d_day, d_month, d_year, 
     trans_type, descriptor, inputs, outputs, balance, 
     owner) 
VALUES 
    ('12 Feb 2012', '12', 'Feb', '2012', 
     'CHQ', 'CHQ 54', '7143.78', '0.00', '10853.96',        
     AES_ENCRYPT('[email protected]', 'example_key_str'))
                                                   HERE^

As a side note, don't use string formatting to insert the query parameters into the query - there is a safer and more convenient way to do it - parameterized query:

sql = """
    INSERT INTO 
        accounts
        (date_string, d_day, d_month, d_year, 
        trans_type, descriptor, inputs, outputs, balance, 
        owner) 
    VALUES 
        (%s, %s, %s, %s, 
        %s, %s, %s, %s, %s, 
        AES_ENCRYPT(%s, 'example_key_str'))"""
cur.execute(sql, (date, d_day, d_month, d_year, ttype, desc, money_in, money_out, bal, owner))

Upvotes: 2

Related Questions