2016-04-19 77 views
0

我想要一個簡單的Python程序提示輸入標題用戶和搜索MySQL數據庫。我有數據庫構建,但我不知道如何正確地查詢它。用戶輸入MySQL數據庫

import MySQLdb 
servername = "localhost"; 
username = "username"; 
password = "password"; 
conn = MySQLdb.connect(user=username,host=servername, passwd=password, db=db) 
cursor = conn.cursor() 
user_input = raw_input("What do you want to watch?:") 
query= ("SELECT * from videos where title LIKE %s") 
cursor.execute(query,user_input) 

IF,硬編碼查詢說 「哪裏標題LIKE '%硬編碼%'」,然後正常工作。我認爲解決方案非常簡單,但我對於我的生活無法想象。任何幫助深表感謝!我嘗試了所有可以在網上找到的變體,但無濟於事。 其他一些我試過的:

query= ("SELECT * from videos where title LIKE CONCAT('%',%s,'%')") 

cursor.execute(query,(user_input,)) 

query= ("SELECT * from videos where title LIKE (search)" 
     "VALUES (%s)", user_input) 

......他們都不工作。

錯誤似乎都圍繞在我身邊路過我的變量USER_INPUT通過正確。

c.execute("SELECT * FROM videos WHERE title LIKE %s", ("%" + user_input + "%",)) 

回答

1

喜歡,你可以創建查詢。在這種情況下,如果沒有,在這我打算使用相同的代碼行,但我發佈了一個完整的代碼爲你的問題

import MySQLdb 
    servername = "localhost" 
    username = "username" 
    password = "password" 
    conn = MySQLdb.connect(user=username,host=servername, passwd=password, db=db) 
    cursor = conn.cursor() 
    user_input = raw_input("What do you want to watch?:") 
    query= ("SELECT * from videos where title LIKE %"+user_input+"%") 
    cursor.execute(query) 
1

我認爲@ddsu給出的解決方案應該已經解決了你的問題:

相關問題