Tag Archives: MySQL

Python and MySQL

If an external application, e.g. written in Python, needs to access MySQL server, take a look at MySQL Option Setting  bind-address . You can also see some practical advise in Ubuntu online help about MySQL. For MySQL Options File format see MySQL Reference Manual.

Ubuntu Machine Steps:

  1. Edit sudo vi /etc/mysql/my.cnf and modify the line with bind-address = 192.168.xxx.xxx [your server address to accept external calls], e.g. add at the end of the file the next lines:
    bind-address = 192.168.xxx.xxx
  2. Restart MySQL daemon:
    sudo service mysql restart

Python Remote Machine Steps:

  1. Proceed as in the tutorialspointPython MySQL Database Access” article, e.g.:
    import MySQLdb
    print "Hello World!"
    # Open database connection
    db = MySQLdb.connect("192.168.xxx.xxx", "testuser", "test123", "testdb" )
    # prepare a cursor object using cursor() method
    cursor = db.cursor()
    # execute SQL query using execute() method.
    cursor.execute("SELECT VERSION()")
    # Fetch a single row using fetchone() method.
    data = cursor.fetchone()
    print "Database version : %s " % data
    # disconnect from server

    Output Sample:

    Hello World!
    Database version : 5.7.15-0ubuntu0.16.04.1

    Possible output in case there is no server running:

    Hello World!
    Traceback (most recent call last):

    _mysql_exceptions.OperationalError: (2003, “Can’t connect to MySQL server on ‘192.168.xxx.xxx’ (10060)”)


Additional Tutorials Links

MySQL Python tutorial