从文件中读取值然后在 sql UPDATE 命令(python 脚本)中传递值
read value from file then pass value in sql UPDATE command(python script)
所以希望这是一个简单的问题,尽管我在使用 google 将它放在一起时遇到了麻烦。我有一个 windows 应用程序,它将值写入一个文本文件,我需要从文本中提取该文件并发送到 mysql。我可以手动完成我需要的一切,但无法从文本文件中提取值并将其发送到更新语句中的 sql(不接受变量)。如果有办法在我的 UPDATE 语句中使用变量,请告诉我。
我要传递的是数据变量。
代码如下:
#!/usr/bin/python
import MySQLdb
file = open('tvalue.txt', 'r')
data = file.read()
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
cursor.execute("UPDATE table1 SET waiting=data where dept='billing'" )
# Commit your changes in the database
db.commit()
# disconnect from server
db.close()
c.execute("UPDATE table1 SET waiting=%s where dept='billing'", (data.strip(),))
应该可以解决问题。
查看 http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html
中的第一个示例
并且切记不要使用串联以避免 SQL 注入。
如果您不希望 waiting 在开头或结尾包含任何新行或空格,请使用 strip。
编辑: 查询必须是元组,在这种情况下,包含单个值,需要 、。
所以希望这是一个简单的问题,尽管我在使用 google 将它放在一起时遇到了麻烦。我有一个 windows 应用程序,它将值写入一个文本文件,我需要从文本中提取该文件并发送到 mysql。我可以手动完成我需要的一切,但无法从文本文件中提取值并将其发送到更新语句中的 sql(不接受变量)。如果有办法在我的 UPDATE 语句中使用变量,请告诉我。
我要传递的是数据变量。
代码如下:
#!/usr/bin/python
import MySQLdb
file = open('tvalue.txt', 'r')
data = file.read()
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
cursor.execute("UPDATE table1 SET waiting=data where dept='billing'" )
# Commit your changes in the database
db.commit()
# disconnect from server
db.close()
c.execute("UPDATE table1 SET waiting=%s where dept='billing'", (data.strip(),))
应该可以解决问题。
查看 http://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html
中的第一个示例并且切记不要使用串联以避免 SQL 注入。
如果您不希望 waiting 在开头或结尾包含任何新行或空格,请使用 strip。
编辑: 查询必须是元组,在这种情况下,包含单个值,需要 、。