David
David

Reputation: 3

Using MySQLdb execute method

I'm having some trouble passing in dynamic variables into my query. Please ignore the poor style. This is what I'm trying to run:

> sql = "SELECT COUNT(*) FROM artifacts WHERE " \
>       "url = '%s' AND " \
>       "source_id = '%s'"
> self.db.execute(sql, (url, source_id))

I get the error:

self.db.execute(sql)
AttributeError: execute

For the life of me, I can't figure out why it's throwing an attribute error. In the User Guide, the example clearly passes in an a correct attribute.

I've been following: http://mysql-python.sourceforge.net/MySQLdb.html

bites on lip eug.

Upvotes: 0

Views: 2661

Answers (1)

aweis
aweis

Reputation: 5596

Just for clarification is your self.db attribute a connection or a cursor. Because you can only call the execute on a cursor!

If your following this example then you can see that there is create a cursor from the connection attribute and this cursor contains the execute method.

here is a small example:

import MySQLdb

## This is the connection to the database
self.db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.dbname)

## To query you need a cursor, this is created here
c = self.db.cursor()

## On the cursor you can execute a sql stamement and look at result
rows = c.execute('select count(*) from test_table')

## To look at the result use a fetch method, here there is only one result so:
print rows.fetchone()

Upvotes: 3

Related Questions