raspberry pi sending data to a XAMPP database - python

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

Related

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

saving sensor data raspberry pi to data base

I'm currently working with raspberry pi and using DHT11 to read temperature and humidity values every second. I have to save these values into a database in real time.
here's my code that showing sensor data every second, i don't know how and where do i insert lines of connection to database.
import RPi.GPIO as GPIO
import dht11
import time
import datetime
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
# read data using pin 7
instance = dht11.DHT11(pin=4)
while True:
result = instance.read()
if result.is_valid():
print("Last valid input: " + str(datetime.datetime.now()))
print("Temperature: %d C" % result.temperature)
#print("Temperature: %d F" % ((result.temperature * 9/5) + 32))
print("Humidity: %d %%" % result.humidity)
time.sleep(1)
first install MySQL db on your system then use PyMySQL or any other library for connection to MySQL from python if using PyMySQL go through this DOC
install library using
pip install PyMySQL
Make connection once so put connection codes on top your while loop
db = PyMySQL.connect("localhost:port","username","password","database_name" )
cursor = db.cursor()
while True:
use cursor for SQL-QUERY execution inside while loop where you get valid results to be stored
sql = "insert into table_name(id,feild1,feild2) values (1,value1,value2);"
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
change the fields table name and connection information as in database and replace values in INSERT statement to your sensor values

How to connect Mysql server via Flask use Python?

I have trouble to connect mysql server via Flask.
I have 4 files: server.py ,testDB.py,testDB2.py and init.py
First , if init.py import testDB.py and I run python server.py, it will print
changes in the database
* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
My user_info table will have user1.
However ,if init.py import testDB2.py and I run python server.py,it just print
* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
My user_info table will not appear user2.
How do I solve this problem ?
The difference between testDb.py and testDB2.py is I defined a function in testDB2.py
init.py
from flask import Flask
app = Flask(__name__)
import testDB
server.py
from Sw import app
if __name__ == '__main__':
port = 8000
host = '0.0.0.0'
app.run(host = host, port = port)
testDB.py
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1",user="root",passwd="1234",db="testdb")
cursor = db.cursor()
sql="""INSERT INTO user_info (user_id, user_email, user_password) VALUES ('user1','00000','000000')"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
print "changes in the database"
db.commit()
except:
# Rollback in case there is any error
print "there is any error"
db.rollback()
db.close()
testDB2.py
import MySQLdb
def testDB():
db = MySQLdb.connect(host="127.0.0.1",user="root",passwd="1234",db="testdb")
cursor = db.cursor()
sql="""INSERT INTO user_info (user_id, user_email, user_password) VALUES ('user2','00000','000000')"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
print "changes in the database"
db.commit()
except:
# Rollback in case there is any error
print "there is any error"
db.rollback()
db.close()
Just as #dirn said in the comment, the reason the database isn't updated in the second case is because you've defined a function, but then never made use of it. Just as any other function in Python, it waits for another line of code to call it into action. When you import it into your init.py file, you have two ways of running it. You can modify init.py like this:
from flask import Flask
app = Flask(__name__)
import testDB2
testDB2.testDB()
Which then runs your function from the init.py file, or you can modify testDB2.py and run the function from there, just by adding testDB() to the end of that file (outside the function, of course).

Parallel connection database data saving with python

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

POSTGRESQL: Connect remote server to host database with Python

Using Python/Psycopg2/PopstgreSQL and Cron.
I'd like to take remote server information(see below) and add it into a PostGreSQL database on the host computer.
Using #!/usr/bin/python
import socket
import commands
import string
import os
hostname = socket.gethostname()
print hostname
ip = commands.getoutput("ifconfig").split("\n")[1].split()[1][5:]
print ip
os = commands.getoutput("lsb_release -d")
print os[13:34]
kernel = commands.getoutput("uname -p")
print kernel
reboot = commands.getoutput("who -b")
print reboot[22:38]
This is the 'connect to database' script:
#!/usr/bin/python
import psycopg2
import sys
try:
conn = psycopg2.connect('host=*** dbname=*** user=*** password=***')
print "Connected to Database"
except:
print "No Connection"
cur = conn.cursor()#cursor_factory=psycopg2.extras.DictCursor)
try:
cur.execute('SELECT * FROM new')
rows = cur.fetchall()
print "\n Show: \n"
for row in rows:
print " ", row
except:
print "Not Working"
I'm able to connect, I'm able to pull the data. I need to combine the two scripts and insert the returned information into the database.
Your local python script would have these lines:
import psycopg2 as db
remote_connection = db.connect('host=that_host dbname=that_db user=user password=pwd')
local_connection = db.connect('host=localhost dbname=local_db user=user password=pwd')

Categories

Resources