Python 将数据发送到 MySQL 数据库

标签 python mysql

我有一个脚本正在运行,每秒更新一次数据库中的某些值。 在脚本的开头,我首先连接到数据库:

conn = pymysql.connect(host= "server",
               user="user",
               passwd="pw",
               db="db",
               charset='utf8')
x = conn.cursor()

我在脚本运行期间(大约 30 分钟)保持连接打开

使用这段代码,我每秒更新一次某些值:

query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
x.execute(query)
conn.ping(True)

但是现在,当我的 Internet 连接中断时,脚本也会崩溃,因为它无法更新变量。我的连接通常会在一分钟内重新建立。 (脚本在移动的车辆上运行。通过 GSM 调制解调器建立互联网连接)

在更新变量之前每次连接到服务器时重新打开是否更好,以便我可以查看连接是否已建立或者是否有更好的方法?

最佳答案

您可以先 ping 连接,而不是在查询之后,因为如果需要,应该重新连接。

设置:

conn = pymysql.connect(host= "server",
                       user="user",
                       passwd="pw",
                       db="db",
                       charset='utf8')

每一秒:

query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
conn.ping()
x = conn.cursor()
x.execute(query)

引用 https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py#L872

连接仍然有可能在 ping() 之后但在 execute() 之前断开,然后会失败。为了处理你需要捕获错误,类似于

from time import sleep

MAX_ATTEMPTS = 10

# every second:
query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission)
inserted = False
attempts = 0

while (not inserted) and attempts < MAX_ATTEMPTS:
    attempts += 1
    try:
        conn.ping()
        x = conn.cursor()
        x.execute(query)
        inserted = True
    except StandardError: # it would be better to use the specific error, not StandardError
        sleep(10) # however long is appropriate between tries
        # you could also do a whole re-connection here if you wanted

if not inserted:
     # do something
     #raise RuntimeError("Couldn't insert the record after {} attempts.".format(MAX_ATTEMPTS))
     pass

关于Python 将数据发送到 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47704358/

相关文章:

php - 从 example.com/myjsonsql.php 提取 json url 到 jquery mobile 无法返回值

php - 如何使用 INNER JOIN 为每个用户获取 1 行

mysql - 错误代码 : 1136. 列计数与第 1 行的值计数不匹配

php - 用户注册时创建 MySQL 表

python登录文件以及wxpython txt ctrl

python - 枕头、OpenJPEG(用于 jpeg2000)和 anaconda

Python的isinstance方法结果对于子类实例是意外的

Python 请求挂起/卡住

python - 无法将字符串转换为浮点型

c# - 检查 ID 行是否存在,如果不存在则创建它