3
如何檢查表中是否存在字段。我需要一個if語句,我相信這樣做。Python:檢查表中是否存在字段
如果行內的字段包含相同的數據,我不想將數據插入行中。
因此,例如我有一個6行的表。前綴,code_id,answer,station_id,時間戳,comport。
用戶將通過控制檯和前綴code_id輸入station_id,並在一行中全部回答。我將它分成三個變量並將它們存儲在數據庫中。
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station_id,timestamp,comport) VALUES(%s, %s, %s, %s, %s, %s)""",(prefix, code_id, answer, station, timestamp,station))
但是在插入語句之前,我想查看用戶輸入的數據是否已經在表中。
我希望我已經夠清楚了。如果不讓我知道,我會編輯這個問題。
編輯:我想這沒有運氣
#test if fields exist before inserting!
query = cursor.execute("""SELECT count(*) FROM scan WHERE prefix = %s and code_id = %s and answer = %s and station_id = %s""",
(prefix, code_id, answer, station,))
if query != 1:
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station_id,timestamp,comport) VALUES(%s, %s, %s, %s, %s, %s)""",
(prefix, code_id, answer, station, timestamp,station))
print 'Thank you for checking into station: ', station ,'please wait for the beep
爲了更加安全,DB上的唯一性約束將是一個好主意。 –
我試過這個'#test if fields exists before inserted! query = cursor.execute(「」「SELECT count(*)FROM scan WHERE prefix =%s and code_id =%s and answer =%s and station_id =%s」「」, (prefix,code_id,answer,station如果查詢!= 1: cursor.execute(「」「INSERT INTO掃描(前綴,code_id,answer, ,%s)「」「, (前綴,code_id,答案,電臺,時間戳,電臺)) 打印'謝謝您檢查站:',電臺,'請等待嗶嗶',但沒有工作 –
「不起作用」是什麼意思? –