MySQL for the Internet of Things

(Steven Felgate) #1

Chapter 6 ■ Building low-Cost MysQl data nodes


$ python
Python 2.7.6 (default, Mar 4 2014, 16:53:21)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.





import mysql.connector
server = {
... 'user': 'root',
... 'password': ,
... 'host': '127.0.0.1',
... 'database': 'employees',
... 'raise_on_warnings': True,
... }
cnx = mysql.connector.connect(**server)





If you get errors at this point, go back and check your connection parameters. It is most likely that your
MySQL server is unreachable, it is down, or you have the wrong credentials specified. If you get no response
from the interactive interpreter, that’s OK—you’ve connected and you are ready to go!
Now, leave the interpreter running and add the following statements. Here we will open a cursor object
for executing queries and retrieving rows. I wrote the loop in a simplistic way to show you how to loop
through all available rows (there are several other, valid ways to write that bit).





cur = cnx.cursor()
cur.execute("SHOW DATABASES")
rows = cur.fetchall()
for row in rows:
... print row
...





When you get the ... (which is a prompt), press Enter and observe the results as shown here. Your list
may be slightly different depending on what databases are on your server.


(u'arduino',)
(u'employees',)
(u'library',)
(u'mysql',)
(u'performance_schema',)
(u'plant_monitoring',)
(u'test',)
(u'test_arduino',)
(u'world',)
(u'world_innodb',)


But we’re not done. There are two more steps needed. We need to close the cursor and connection and
then exit the interpreter.





cur.close()
True
cnx.close()
quit()




Free download pdf