Python/MySQL syntax error

2707
1
05-11-2014 11:46 AM
DavidMcMahon
New Contributor
Hi All,

First off I'm new to Python coming from a Java/C++ background. I've created a simple Python program that will connect to a database and query it returning the results from the querys. I receive a nasty syntax error message which I cannot spot in my code. Maybe one of ye can? Im running Python 2.7 and MySQL 5.6. Wingware is the IDE I'm using on a Windows 8.1 OS.

import MySQLdb

class Database:
    
    host = "localhost"
    user = "testuser"
    passwd = "password"
    db = "test"
    
    def __init__(self):
        self.connection = MySQLdb.connect(host = self.host,
                                          user = self.user,
                                          passwd = self.passwd,
                                          db = self.db
                                         )
    def query(self, q):
        cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute(q)
        
        return cursor.fetchall()
    
    def __del__(self):
        self.connection.close()


if __name__ == "__main__":
    db = Database()
    
    q = "use test"
    db.query(q)
    
    q = "DELETE FROM testtable"
    db.query(q)
    
    q = """
    INSERT INTO testtable
    ('name', 'age')
    VALUES
    ('Mike',39),
    ('Michael',21),
    ('Angela', 21)
    """
    
    db.query(q)
    
    q = """
    SELECT * FROM testtable
    WHERE age = 21
    """
    
    people = db.query(q)
    
    for person in people:
        print "Found: {0}".format(person['name'])


This is the error message:
ProgrammingError: (1064, "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 ''name', 'age')\n    VALUES\n    ('Mike',39),\n    ('Michael',21),\n    ('Angela', 21' at line 2")

Thanks in advance guys!
Dave.
Tags (2)
0 Kudos
1 Reply
DavidMcMahon
New Contributor
Hey all, never mind I fixed the bug. The problem was with the quotation marks within the MySQL syntax.

Solution:
 q = """
    INSERT INTO testtable
    (name, age)
    VALUES
    ('Mike',39),
    ('Michael',21),
    ('Angela', 21)
    """


Thanks anyway!!
0 Kudos