简体   繁体   中英

How to refresh Mysql connection?

I have a program using Python + python mysql connector + Mysql which is installed in a network and uses the same database. How do I refresh a connection without restarting the program on other Machines?

The Program is installed in more than one Machine and connects to the same Mysql database which is located on a Server. The program is working properly, but, when a new data is entered or modified "SQL INSERT, UPDATE.... Statments" from one machine is not reflected in all other Machines until the program is restarted, which means that a new connection is necessary to show the new database data.

So, I would like to know how to refresh the connection without restarting the program on other machines.

Here is the sample Connection code:

import mysql.connector as mc

conn = mc.connect(host='host', user='user', passwd='passw', db='db_name', port=port_number)

cur = conn.cursor()

How to refresh This Connection while the program is running?

After inserting or updating, you should do a commit to make sure all data it's writed to the DB. Then it will be visible for everyone:

conn.commit()

closing and reopening connection may also solve your problem, see following example in loop

import mysql.connector as mc

conn = mc.connect(host='host', user='user', passwd='passw', db='db_name', port=port_number)

while True:
    # check if youre connected, if not, connect again
    if (conn.is_connected() == False):
        conn = mc.connect(host='host', user='user', passwd='passw', db='db_name', port=port_number)

    cur = conn.cursor()
    sql = "INSERT INTO db_name.myTable (name) VALUES (%(val)s);"
    val = {'val':"Slim Shady"}
    cur.execute(sql,val)
    conn.commit()
    conn.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM