I want to make parallel database saving in my system. I have two destination that the database will be saved. Firstly in the local computer (so I'm using localhost instead of the IPaddress) and the remote PC (i'm using the IP address to access it). Here is my code in 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!"
I want to ignore the dbConn2 althought the connection is not connect. The connection is using ethernet LAN. So when I unplug the LAN, I hope my program still running (still send to localhost).
The result of my code above is when i'm unplugging the ethernet LAN, data sending to localhost has stopped. I try to make changes but still get the problem. I'm using python 2.7. I need your help, thank you :)
Related
I am new to Python and mySQL and I am trying to get the following Python script running as a CGI on an hosted webserver:
#!/usr/bin/python3
import cgi
import sys
sys.path.append("PATH TO SIDE PACKAGES DUE TO MISSING ROOT ACCESS")
import mysql.connector
from mysql.connector import Error
print('Content-type: text/html') # the mime-type header.
print() # header must be separated from body by 1 empty line.
try:
connection_config_dict = {
'user': 'MY_USER',
'password': 'MY_PASSWORD',
'host': 'rdbms.strato.de',
'database': 'MY_DATABASE',
}
connection = mysql.connector.connect(**connection_config_dict)
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("Your connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
Unfortunately, this results in the following error message:
Error while connecting to MySQL 2055: Lost connection to MySQL server at 'rdbms.strato.de:3306',
system error: 104 Connection reset by peer
I looked up older threads with the error message and while I could find both separately, I did not find them in this combo, therefore I hope there might be someone having an idea for a solution before I deal with the horrible customer service of my provider again. To me as a newbie it seems like the server declines the connection, even though I am coming from inside the network (running as a CGI on the server).
Some more information about the environment: The Python version is 3.8.1, mySQL server version 5.7, mysql_connector_python version 8.0.23. Since it is a hosted webserver I do not have root access, therefore I installed additional modules with pip --user via ssh and added the path to the script which works fine with other modules like requests. I am also certain that the mySQL login data is correct, since it works flawlessly with a PHP script.
Thanks in advance for helping out!
I am new to Python and I am trying to make a script that connects to a remote windows machine and change mdb file there. I can’t figure out how to work with the WMI library.
When I need to change mdb file (Access database) on my machine, I just use pyodbc connect. For example like this:
connStr = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb)};'
r'DBQ=C:\Komax\Data\Topwin\DatabaseServer.mdb;')
cursor = connStr.cursor()
But now I need to run code on my machine so that it modifies the file (mdb) on the other machine. It seems like I have to use this code below to connect to remote machine, but I don't know what to do next, how to use connection. Please, help me to solve the problem :)
ip = "192.168.18.74"
username = "admin"
password = "komax"
from socket import *
try:
print("Establishing connection to %s" % ip)
connection = wmi.WMI(ip, user=username, password=password)
print("Connection established")
except wmi.x_wmi:
print("Your Username and Password of "+getfqdn(ip)+" are wrong.")
I have the following code in python for sending data to a mysql database
import time
import datetime
import MySQLdb
from time import strftime
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
PIR_PIN = 21
GPIO.setup(PIR_PIN, GPIO.IN)
# Variables for MySQL
db = MySQLdb.connect(host="*******", user="root",passwd="*****", db="sensor1")
cur = db.cursor()
while True:
i = GPIO.input(PIR_PIN)
print i
datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
print datetimeWrite
sql = ("""INSERT INTO templog (datetime,temperature) VALUES (%s,%s)""",(datetimeWrite,i))
try:
print "Writing to database..."
# Execute the SQL command
cur.execute(*sql)
# Commit your changes in the database
db.commit()
print "Write Complete"
except:
# Rollback in case there is any error
db.rollback()
print "Failed writing to database"
cur.close()
db.close()
break
My problem is that my XAMPP server is installed in pc where I want to view the the data from raspberry pi in mysql database.
So for getting the connection established what should I write in host= "?"
The connection-string should be like this:
db = MySQLdb.connect(host="192.168.0.xxx", user="root",passwd="*****", db="sensor1")
See this Question
Host will be IP address of your system on which XAMPP is installed e.g. 192.168.x.x
def hbasePopulate(self,table="abc",MachineIP="xx.xx.xx.xx"):
connection=happybase.Connection(MachineIP,autoconnect=True)
tablename=Reptype.lower()+'rep'
print "Connecting to table "
print tablename
try:
table=connection.table(tablename)
for key,data in table.scan():
print key,data
print table
#except IOError as e:
except:
print "Table does not exists,creating"
self.createTable(table=table,machineIP=machineIP)
with table.batch() as b:
with open('xxx.csv','r') as queryFile:
for lines in queryFile:
lines=lines.strip("\n")
splitRecord=lines.split(",")
key=splitRecord[0]
key=key.replace("'","")
val=",".join(splitRecord[1:])
val=ast.literal_eval(val)
table.put(splitRecord[0],val)
for key,data in table.scan():
print key,data
def createTable(self,table="abc",MachineIP=""):
connection=happybase.Connection(MachineIP,autoconnect=True)
print "Connection Handle",connection
tname=table.lower()
tablename=str(tname)
print "Creating table : "+table+", On Hbase machine : "+MachineIP
families={"cf":{} ,} #using default column family
connection.create_table(table,families=families)
print "Creating table done "
Every time I run this script it populated data to hbase table but it leaves a connection open. When I check using netstat -an I see the connection count has increased which persists even after the script completes.
Am I missing something? Do we need to explicitly close connection?
Thanks for helping.
Got the solution .Turns out to be this
try:
connection.close()
except Exception as e:
print "Unable to close connection to hbase "
print e
If the program exited, any network connections are automatically closed. What you're likely seeing is the TIME_WAIT state for already closed connections.
Wondering if there is a way to use a python script to attempt a connection to a group mysql database hosts? Ideally there would be X number of hosts and it would try connecting to each, then fail if no connection could be made. I do not believe MySQLdb.connect is capable of handling multiple hosts, maybe I am wrong.
mysqldb.connect is perfectly ok with connecting to multiple hosts:
try:
conn1 = mysqldb.connect(...)
conn2 = mysqldb.connect(...)
...
except: # add specific exception here
... # support failure when connecting