【发布时间】:2019-05-28 19:33:22
【问题描述】:
我有一个名为 led_status 的表和一个名为“test_led”的字段:
mysql> describe led_status;
+------------------------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------------------+------------+------+-----+---------+-------+
| test_led | varchar(5) | NO | | NULL | |
+------------------------------+------------+------+-----+---------+-------+
我正在尝试使用以下代码输入“TRUE”或“FALSE”(不是 int 1 或 0)字符串:
def write_database_value(table,field,value):
connect = mysql.connector.connect(user=db_info.username,
password=db_info.password,
host=db_info.servername,
database=db_info.database)
cursor = connect.cursor()
cursor.execute(("UPDATE %s SET %s = %s") % (table, field, value))
connect.commit()
cursor.close()
connect.close()
def read_database_value(table,field):
connect = mysql.connector.connect(user=db_info.username,
password=db_info.password,
host=db_info.servername,
database=db_info.database)
cursor = connect.cursor(buffered=True)
cursor.execute(("SELECT %s FROM %s") % (field, table))
for data in cursor:
database_value = data
cursor.close()
connect.close()
return database_value
从这个脚本中调用:
def get_led_status(led):
led_status = read_database_value("led_status", led)
led_status = (led_status[0])
return led_status
def is_pool_pump_running():
pool_running = get_led_status("test_led")
if pool_running == "TRUE":
print("Pool Pump is Running, shutting it off now")
write_database_value("led_status","test_led","FALSE")
else:
print("Pool Pump is NOT Running, turning it on now")
write_database_value("led_status","test_led","TRUE")
但是,每次我运行脚本时,它都会将我的“TRUE”更改为 1,将“FALSE”更改为 0。
我正在从平面文件切换到数据库,并且我的所有代码(到目前为止 4000 行)都使用“TRUE”和“FALSE”,所以我真的不想为了使用而重写它1 和 0,而不是“TRUE”和“FALSE”。
任何想法将不胜感激。
【问题讨论】:
-
两个重要的事情:(1)你没有在SQL上使用
%字符串格式,它会导致SQL注入漏洞(2)划分数据及其表示:0/@987654327 @ 或 Python 中的False/True是用于在计算机中存储和处理的数据,字符串"TRUE"和"FALSE"是您将其呈现给人类的方式。 -
谢谢@KlausD。我的理解是 %s 是 正确的方法,并且 cursor.execute 专门防止 SQL 注入问题。 Stack Exchange 上的Posts 为我指明了这个方向。这些信息不正确吗?其次,正如我上面所说,我正在从一个使用真/假表示的平面文件迁移,当我迁移到数据库设计时,我真的不想将所有代码重写为 0/1,因此我想坚持将 true/false 作为 varchar 而不是 0/1 作为 bit 或 tinyint。
-
重要的区别是字符串和参数之间的
%。必须是逗号才能安全。 -
@KlausD。啊!!!我想错了%!我会详细阅读并更改它。