使用MySQLdb的execute方法
我在把动态变量传入查询时遇到了一些麻烦。请忽略我的代码风格不好。这是我尝试运行的代码:
> sql = "SELECT COUNT(*) FROM artifacts WHERE " \
> "url = '%s' AND " \
> "source_id = '%s'"
> self.db.execute(sql, (url, source_id))
我遇到了这个错误:
self.db.execute(sql)
AttributeError: execute
我真搞不懂为什么会出现属性错误。在用户指南里,例子里明明传入了一个正确的属性。
我一直在参考这个链接: http://mysql-python.sourceforge.net/MySQLdb.html
咬着嘴唇 真让人头疼。
1 个回答
3
为了更清楚地说明,你的self.db属性是连接对象还是游标对象呢?因为你只能在游标上调用execute方法!
如果你参考了这个示例,你会看到是从连接对象创建了一个游标,而这个游标里有execute这个方法。
下面是一个简单的例子:
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()