I am making a database class in python to help with managing my mysql database.
The code below works until the last line
import MySQLdb
class Database:
...
def insert(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
except:
self.connection.rollback()
...
db = Database()
db.insert('INSERT INTO items (title) VALUES ("tester2");')
mystring = "TEST"
db.insert('INSERT INTO items (title) VALUES (%s);', mystring)
The last line causes the error:
db.insert('INSERT INTO items (title) VALUES (%s);', mystring)
TypeError: insert() takes exactly 2 arguments (3 given)
I have tried to rearrange the contents inside the db.insert's parens but I cannot figure out the syntax.
For instance I have tried this as well, but it neither inserts nor gives an error:
db.insert('''"INSERT INTO items (title) VALUES (%s);", mystring''')
My question is can I get the syntax right in order to insert using the %s, or do I have to change my class's insert function?
EDIT 1
I have tried the suggested lines:
db.insert("INSERT INTO items (title) VALUES (%s);"% mystring)
and
db.insert('INSERT INTO items (title) VALUES {value};'.format(value=mystring))
neither gave errors nor inputed any value into the database
EDIT 2
Whole code for main that calls the Database class:
if name == "main":
db = Database()
mystring = 'Tester1'
mystring2 = 'Tester2'
db.insert('INSERT INTO items (title) VALUES ("Tester3");') #works
db.insert("INSERT INTO items (title) VALUES (%s);" % mystring) #does not work
db.insert('INSERT INTO items (title) VALUES {value};'.format(value=mystring2)) #does not work
print db.query('SELECT * FROM items;')
db = Databasewhere's the parentheses ?executecorrectlyexcept Exception as eand addprint ebefore rollback