2011-03-13 46 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