0

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?

0

3 Answers 3

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

mysql-connector-python has cmd_refresh() method which refreshes the connection and fetchs the most recent data, so to refresh it I used conn.cmd_refresh(1). Thanks for your answer and sorry for later comment.
1

You can reconnect the database connection. It will fix the problem.

self.mycursor.close()
self.db.reconnect()
self.mycursor = self.db.cursor(dictionary=True)

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.