Created
April 11, 2018 20:12
-
-
Save marquesghm/81f071bab2933168c42f9da50054aad6 to your computer and use it in GitHub Desktop.
Exemplo conexão com MySQL- Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
db_hostname = "localhost" # MySQL host ip address or name | |
db_database = "mqtt" # MySQL database name | |
db_username = "mqttuser" # MySQL database user name | |
db_password = "mqttpass" # MySQL database password | |
import MySQLdb as mdb | |
import time | |
print "Try connect database" | |
db_connected = 0 | |
while db_connected == 0: | |
try: | |
con = mdb.connect(db_hostname, db_username, db_password, db_database) | |
db_connected = 1 | |
except: | |
print "Warning: No database (connection) found. Retry in one minute." | |
time.sleep(60) | |
pass | |
with con: | |
cur = con.cursor() | |
cur.execute("INSERT INTO messages (topic , qos, message) VALUES (%s, %s, %s)", ("iseedtest", 0, "test14")) | |
print "MySQL INSERT INTO messages" | |
with con: | |
cur = con.cursor() | |
cur.execute('SELECT timestamp, topic, message FROM messages WHERE topic = "iseedtest"') | |
if cur.rowcount > 0: | |
rows = cur.fetchall() | |
payload = "[" | |
jsonnext = "" | |
for row in rows: | |
payload = payload + jsonnext + '{"time":"' + str(row[0]) +'"' | |
payload = payload + ',"topic":"' + str(row[1]) + '"' | |
payload = payload + ',"value":"' + str(row[2]) + '"}' | |
jsonnext = ",\n" | |
payload = payload + "]" | |
else: | |
payload = "none" | |
print payload |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment