python数据库请求未更新

时间:2019-05-13 19:36:35

标签: python mariadb mariadb-connect-engine

我正在使用python脚本从数据库中提取数据,该脚本可在启动时工作,但是当我更改数据库中的值时不会更新。

该脚本最初连接到数据库,然后选择id等于1的所有内容(其中有许多列我打算使用)

然后使用车库列中的内容更新全局变量garageHeating,可以说它在启动时等于0。

while循环会打印出该变量,该变量在开始时将为0

如果我将数据库中的列车库更改为10,则python脚本将保持为0。它不会更新我认为应该执行的全局变量

我的脚本在下面

import mysql.connector as mariadb

mariadb_connection = mariadb.connect(
  host="localhost",
  user="garage",
  passwd="*******",
  database="mydb"
  )
cursor = mariadb_connection.cursor()

garageHeating = 0 

def readDbHeating():
   global garageHeating
   result = []
   try:
      cursor.execute ("SELECT * FROM heating WHERE id = '1'")
      for reading in cursor.fetchall():
         result.append (reading)
         garageHeating = result[0][8]
   except () as e:
      print (e)

while 1:
   readDbHeating()
   print garageHeating

我已经编辑了下面所示的上面的代码,以显示函数外部的全局变量,并在try命令中打印出结果。在从数据库中首次提取数据后,脚本仍然显示第一组数据,但是如果我更改数据库记录,则不会更新为新数据,我仍然遇到相同的问题。

import mysql.connector as mariadb

mariadb_connection = mariadb.connect(
  host="localhost",
  user="garage",
  passwd="14Odiham",
  database="mydb"
  )
cursor = mariadb_connection.cursor()

global garageHeating

def readDbHeating():
   result = []
   try:
      cursor.execute ("SELECT * FROM heating WHERE id = '1'")
      for reading in cursor.fetchall():
         result.append (reading)
         garageHeating = result[0][8]
         print garageHeating
         print result
   except () as e:
      print (e)

while 1:
    readDbHeating()
    #print garageHeating

2 个答案:

答案 0 :(得分:1)

您必须在执行查询之前调用MySQLdb.connections.Connection.commit或在连接对象上设置autocommit

在查询之前提交

def readDbHeating():
   global garageHeating
   result = []
   try:
      # commit
      mariadb_connection.commit()
      cursor.execute ("SELECT * FROM heating WHERE id = '1'")
      for reading in cursor.fetchall():
         result.append (reading)
         garageHeating = result[0][8]
   except () as e:
      print (e)

在创建连接时自动提交

mariadb_connection = mariadb.connect(
  host="localhost",
  user="garage",
  passwd="14Odiham",
  database="mydb",
  # Auto commit
  autocommit=True
  )

创建连接后自动提交

mariadb_connection.autocommit(True)

答案 1 :(得分:0)

我似乎正在工作。我必须打开数据库连接,然后在函数内关闭连接,如下所示。这与我过去使用mysql完成的操作不同,但至少现在可以使用

import mysql.connector as mariadb
import time

garageHeating = 0

def readDbHeating():
   mariadb_connection = mariadb.connect(
     host="localhost",
     user="garage",
     passwd="14Odiham",
     database="mydb"
     )
   cursor = mariadb_connection.cursor()
   result = []
   try:
      cursor.execute ("SELECT * FROM heating WHERE id = '1'")
      for reading in cursor.fetchall():
         result.append (reading)
   except () as e:
      print (e)
   finally:
    #closing database connection.
    if(mariadb_connection.is_connected()):
        mariadb_connection.close()
        print("connection is closed")
   return (result)


while 1:
   test = readDbHeating()
   print test
   time.sleep(1)