搜索文件并在数据库中插入值

时间:2014-08-21 20:23:09

标签: python database

我正在编写这个脚本来打开一个文件并在其中搜索一个字符串,在这种情况下" Games"一旦遇到它就打开数据库连接并插入一个" 1"在一个名为" feature"的列中,代码工作正常,但它不会将值1插入该特定列。

#!/usr/bin/python
flag1=0
flag2=0
flag3=0
#open a file 
file = open("foo.txt", mode="r")
print 'Brian'
for line in file:
    if "Games" in line and flag1==0:
        print 'found "Games " in file'
        flag1=1            
                # Open database connection
        import MySQLdb
        db = MySQLdb.connect("apps_dev@test.net","apps_dev","TeStUsEr","apps_dev" )
           print 'insert value 1 '
                # prepare a cursor object using cursor() method
        cursor = db.cursor() # to traversal the records in a DB
                # Prepare SQL query to INSERT a record into the database.
        sql = """INSERT INTO (Feature) VALUE (1)"""

        try:
                # Execute the SQL command
            cursor.execute(sql)
                # Commit your changes in the database
            db.commit()
        except:
                # Rollback in case there is any error
            db.rollback()
                # disconnect from server
    db.close()

1 个答案:

答案 0 :(得分:0)

我认为您的查询stmt存在问题, 它应该是:

Insert into TheTableName(Feature) values (1)

在您的情况下,您没有定义将1放入

的表