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」とは対照的です。
どんな考えでも大歓迎です。
入力を提供してくれたすべての人に感謝します。たくさん掘り下げた後、私は自分の問題を理解しました。どうやら、プリペアドステートメントでテーブル名をパラメータ化することはできません。これはまさに私が上でやろうとしていたことです。@ConspicuousCompilerの答えを見つけたPOSTはそのステートメントで死んでいた。
問題は私のwrite_database_value()
機能にありました。これは、必要に応じて機能する正しい関数です。
def write_database_value(table,column,value):
try:
connection = mysql.connector.connect(user=db_info.username,
password=db_info.password,
host=db_info.servername,
database=db_info.database)
cursor = connection.cursor(buffered=True)
sql_update = "UPDATE " + table + " SET " + column + " = %s"
cursor.execute(sql_update, (value,))
connection.commit()
cursor.close()
connection.close()
except Error as error :
print("Failed to Update record in database: {}".format(error))
finally:
if(connection.is_connected()):
connection.close
大きな変化:
から: cursor.execute(("UPDATE %s SET %s = %s") % (table, field, value))
これに:
sql_update = "UPDATE " + table + " SET " + column + " = %s"
cursor.execute(sql_update, (value,))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加