所以,我有一个带字段的数据库(单词TEXT,par1 INTEGER)。 所以,我用一些文本解析一些txt文件并得到单词列表([word1,word2,word3])。我需要检查db中列表中的单词,如果db中的单词我更改了par1,如果不是db,请将此单词添加到db。 我该怎么办?
答案 0 :(得分:1)
如果您正在使用MySQL,请参阅the top answer here以获得使用Python连接数据库的精彩介绍。
根据您访问的数据库,您必须更改前两行:
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;也许你可以解释你想要改变它的内容,以及在插入新记录时你想要设置它的内容?