2016-05-12 22 views
-1

所以,我有一個數據庫與字段(word文字,par1 INTEGER)。 因此,我解析了一些txt文件,其中有一些文本並獲取單詞列表([word1,word2,word3])。我需要檢查是否從db列表中的單詞,如果db中的單詞我更改par1,如果不在db中 - 將這些單詞添加到db。 我該怎麼辦?搜索/添加分貝

+0

我們不能幫你,除非你發佈了一些你寫的代碼來嘗試你的問題。 – Seekheart

回答

1

請參閱the top answer here瞭解如何使用MySQL連接到數據庫。

根據您正在訪問哪些數據庫,你將不得不改變前兩行:

import MySQLdb 
#Make a connection to the database where your fields are stored 
db = MySQLdb.connect("host machine", "dbuser", "password", "dbname") 
cur = db.cursor() #Create a cursor object 

#Replace this with a line parsing your text file 
words = ['word1','word2','word3'] 

#Loop through each word found in the file 
for word in words: 
    #If the word was found in the 'word' column, we arbitrarily change its par1 
    if cur.execute("SELECT COUNT(word) FROM YourTable WHERE par1 = '{}'".format(word)): 
     cur.execute("UPDATE YourTable SET par1 = par1 + 1000 WHERE word = '{}'".format(word)) 
    else: #But, if it did not exist, add it 
     cur.execute("SELECT MAX(par1) FROM YourTable") #Execute a query 
     maxIndex = db.cursor.fetchall() #Get a result 
     cur.execute("INSERT INTO YourTable ('{}',{})".format(word,maxIndex+1)) 

#Be sure to close the connection when done 
db.close 

你會替換爲文本文件的解析詞的明確定義;還要將「YourTable」替換爲數據庫中表的實際名稱。

另外,我正在隨意改變par1,正如你所提到的那樣;也許你可以解釋你想要改變它的內容,以及插入新記錄時你想要設置的內容?