This page looks best with JavaScript enabled

MySQL Connection from Python

 ·  🎃 kr0m

Many times we need to consult or store certain information from our python scripts, a good way to do it is by using a MySQL database for this purpose, we simply import the library in charge of the internal management of the connection and that’s it, we can now execute SQL queries.

The script is not complicated, we just import the library, connect to the server, prepare the query and execute it.

#! /usr/bin/python
import os
import sys

try:
    import MySQLdb as mdb
except ImportError:
    print "Please install dev-python/mysql-python package"
    sys.exit(1)

try:
        db=mdb.connect("127.0.0.1", user="root", passwd="XXXXXX",db="prueba")
except mdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit(1)

cursor=db.cursor()
sql="SELECT * from pythonTest;"
cursor.execute(sql)
for n in cursor.fetchall():
        print "Valor: " + str(n[0])

cursor.close()
db.close()
If you liked the article, you can treat me to a RedBull here