2016-07-05 32 views
1

我正在使用Canari Framework在Malteog中構建一系列掃描MySQL數據庫並將結果作爲實體返回的變換。在SQL中搜索字段以查看它是否包含python變量

我已經得到了SQL語句中LIKE操作符的全部工作欄。這裏是代碼:

#=========================================================================== 
# Request and set target from graph 

target = (request.entity.value) 

#=========================================================================== 
# Extract message column and check against target entity 

statement = (
    "SELECT * FROM tableT.TTO WHERE Text LIKE %(tq)s" 
) 

cursor.execute(statement, { 'tq': target }) 

results = cursor.fetchall() 

#=========================================================================== 
# Create response entities based on SQL output 

for r in results: 

    e = getTTO(target) 
    e.From = r[0] 
    e.Text = r[1] 
    e.date = r[2] 
    e.iconurl = 'http://local.paterva.com/phrase.png' 
    response += e 

它的工作原理,但它只是返回確切的匹配。我需要它來檢查TEXT列以查看條目是否包含任何提及的變量「target」。我花了一天的最佳時間讓python變量傳入,但我無法讓它返回除完全匹配之外的任何內容。

+0

您可能正在尋找[全文搜索(http://dev.mysql.com/doc/refman/5.7/en/fulltext-自然language.html)。 – syntonym

回答

0

SQL LIKE操作符在值(取決於您是否想要「開始於」,「endswith」或「contains」搜索)之前和/或之後需要特殊的「通配符」標記(MySQL中的「%」)。你必須周圍添加你的觀點的通配符,即:

cursor.execute(statement, {'tq': "%{}%".format(target)}) 

還要注意的是cursor.fetchall()將加載在內存中的整個結果集,這是要求MemoryErrorcursor對象iterables和它的安全使用他們的方式:

cursor.execute(statement, {'tq': "%{}%".format(target)}) 
for row in cursor: 
    do_something_with(row) 
+0

我明白了!非常感謝。我沒有花太多時間用SQL,所以我只是深入瞭解這些細節。與大多數項目一樣......沒有「學習時間」的空間。這雖然清除了。好東西。 –

相關問題