首页 > 解决方案 > mysql多进程 - 写入时获取数据

问题描述

我需要尽快从传感器记录数据。因此,我启动了一个进程,通过 python 中的并行运行线程将数据连续写入 MySQL 数据库。

在我启动这个线程之后,我需要经常获取数据库的一些数据,这些数据已经被活动线程插入。

问题是,在线程运行时我无法访问数据。停止线程后,我可以从数据库中读取数据。我还尝试在每一行上“提交”每一行,但它仍然不起作用。

这是我的测试脚本:

import mysql.connector
from mysql.connector import pooling
import datetime, json, threading


mydb = mysql.connector.pooling.MySQLConnectionPool( pool_size = 3,
                                                    host = "localhost",
                                                    user = "user",
                                                    passwd = "password",
                                                    database = "any"
                                                )

connection = mydb.get_connection()
connection_1 = mydb.get_connection()

my_cursor = connection.cursor()
my_cursor_1 = connection_1.cursor()

def continous_process():
    while True:
        cmd = "INSERT INTO config (config_json, date) VALUES (%s, %s)"
        date = datetime.datetime.now()
        values = (json.dumps("something"), date)
        my_cursor.execute(cmd, values)
        my_cursor.execute("COMMIT")

def get_last_config():
        my_cursor_1.execute("SELECT entry_id FROM config ORDER BY entry_id DESC LIMIT 1")
        print(my_cursor_1.fetchall()[0])

my_thread = threading.Thread(target=continous_process)
my_thread.start()
print(my_thread.is_alive())

while True:
    print(get_last_config())

connection.release()每次进入后是否需要释放连接?我期待一个几乎是“实时”的高性能解决方案。

标签: pythonmysqlmultithreading

解决方案


推荐阅读