来自python的重复mysql查询

l2osamch  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(345)

我需要从python中反复查询mysql数据库,因为数据正在快速变化。每次读取数据时,都会将其传输到一个列表中。
我假设只要将查询放入循环中,就可以在每次迭代时从数据库中获取数据。似乎不是。

import mysql.connector
from mysql.connector import Error
from time import sleep

# Create empty list to store values from database.

listSize = 100
myList = []

for i in range(listSize):
    myList.append([[0,0,0]])

# Connect to MySQL Server

mydb = mysql.connector.connect(host='localhost',
                               database='db',
                               user='user',
                               password='pass')

# Main loop

while True:

    # SQL query
    sql = "SELECT * FROM table"

    # Read the database, store as a dictionary
    mycursor = mydb.cursor(dictionary=True)
    mycursor.execute(sql)

    # Store data in rows
    myresult = mycursor.fetchall()

    # Transfer data into list
    for row in myresult:
        myList[int(row["rowID"])] = (row["a"], row["b"], row["c"])

        print(myList[int(row["rowID"])])

    print("---")
    sleep (0.1)

我尝试过使用fetchall、fetchmany和fetchone。

hl0ma9xz

hl0ma9xz1#

您需要在每次查询之后提交连接。这将提交当前事务,并确保下一个(隐式)事务将获取上一个事务处于活动状态时所做的更改。


# Main loop

while True:

    # SQL query
    sql = "SELECT * FROM table"

    # Read the database, store as a dictionary
    mycursor = mydb.cursor(dictionary=True)
    mycursor.execute(sql)

    # Store data in rows
    myresult = mycursor.fetchall()

    # Transfer data into list
    for row in myresult:
        myList[int(row["rowID"])] = (row["a"], row["b"], row["c"])

        print(myList[int(row["rowID"])])

    # Commit !
    mydb.commit()
    print("---")
    sleep (0.1)

这里的概念是隔离级别。从文件(我的):
可重复读取
这是innodb的默认隔离级别。同一事务中的一致读取读取第一次读取所建立的快照。

ql3eal8s

ql3eal8s2#

我会做一些改变。首先,在while循环之前声明游标。我也会做一个缓冲游标。最后,在文件完成后关闭游标和db。希望这有帮助。

import mysql.connector
from mysql.connector import Error
from time import sleep

# Create empty list to store values from database.

listSize = 100
myList = []

for i in range(listSize):
    myList.append([[0,0,0]])

# Connect to MySQL Server

mydb = mysql.connector.connect(host='localhost',
                               database='db',
                               user='user',
                               password='pass')
mycursor = mydb.cursor(buffered=True, dictionary=True)

# Main loop

while True:

    # SQL query
    sql = "SELECT * FROM table"

    # Read the database, store as a dictionary
    mycursor.execute(sql)

    # Store data in rows
    myresult = mycursor.fetchall()

    # Transfer data into list
    for row in myresult:
        myList[int(row["rowID"])] = (row["a"], row["b"], row["c"])

        print(myList[int(row["rowID"])])

    print("---")
    sleep (0.1)
mycursor.close()
mydb.close()

相关问题