2011-03-13 44 views
0

我在动态变量传入我的查询时遇到了一些麻烦。请忽略可怜的风格。这就是我试图运行:使用MySQLdb执行方法

> 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 

对于我的生活,我想不通为什么它抛出一个属性的错误。在用户指南中,该示例清楚地传递了正确的属性。

我一直在关注:上嘴唇 EUG http://mysql-python.sourceforge.net/MySQLdb.html

叮咬。

回答

3

只是澄清是你的self.db属性的连接或游标。因为你只能在游标上调用execute!

如果以下this example那么你可以看到有创建的连接属性的光标,此光标包含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() 
+0

AHHHHH!这开始有意义。这是我做了什么现在: 高清db_connect(个体经营): 数据库句柄= _mysql.connect(主机= self.host, 端口= self.port, 用户= self.user, passwd文件= self.passwd, db = self.dbname) self.db = dbhandle.cursor() - 这是否合理,因为它似乎还没有工作。 – David 2011-03-13 14:50:47

+0

没关系。我正在使用_mysql而不是MySQLdb,它显然是它的包装。 D'哦。谢谢! – David 2011-03-13 14:54:18