用python保存并行连接数据库数据

时间:2016-08-23 16:29:09

标签: python mysql

我想在我的系统中保存并行数据库。我有两个目的地,数据库将被保存。首先在本地计算机上(所以我使用localhost而不是IPaddress)和远程PC(我使用IP地址访问它)。这是我在python中的代码:

import serial
import MySQLdb

dbConn = MySQLdb.connect(host="localhost",user="root",passwd="rooting",db="database") or die ("could not connect to database")
dbConn2 = MySQLdb.connect(host="192.168.1.132",user="bobi",passwd="rooting",db="database") or die ("could not connect to database")

cursor = dbConn.cursor()
cursor2 = dbConn2.cursor()

device = '/dev/ttyACM0'

while 1:
    try: 
        arduino = serial.Serial(device,9600)
    except:
        print "Failed to connect on",device

    try:
        data = arduino.readline()
        try:
            print("Frequency : " + data)
            cursor.execute("INSERT INTO frequency (Value) VALUES (%s)",(data))
            dbConn.commit()
        except dbConn.IntegrityError:
            print "failed to insert data to localhost"

        try:
            cursor2.execute("INSERT INTO frequency (Value) VALUES (%s)",(data))
            dbConn2.commit()
        except dbConn2.IntegrityError:
            print "failed to insert data to remote computer"

    except:
        print "Failed to get data from Arduino!"

我想忽略dbConn2,但是连接没有连接。连接使用以太网LAN。所以当我拔掉局域网时,我希望我的程序仍在运行(仍然发送到localhost)。 我上面的代码的结果是当我拔掉以太网LAN时,发送到localhost的数据已经停止。我尝试进行更改但仍然遇到问题。我使用的是python 2.7。我需要你的帮助,谢谢你:)。

0 个答案:

没有答案