Accessing MySQL database using MySQLdb

suggest change

The first thing you need to do is create a connection to the database using the connect method. After that, you will need a cursor that will operate with that connection.

Use the execute method of the cursor to interact with the database, and every once in a while, commit the changes using the commit method of the connection object.

Once everything is done, don’t forget to close the cursor and the connection.

Here is a Dbconnect class with everything you’ll need.

import MySQLdb

class Dbconnect(object):

    def __init__(self):

        self.dbconnection = MySQLdb.connect(host='host_example',
                                           port=int('port_example'),
                                           user='user_example',
                                           passwd='pass_example',
                                           db='schema_example')
        self.dbcursor = self.dbconnection.cursor()

    def commit_db(self):
        self.dbconnection.commit()

    def close_db(self):
        self.dbcursor.close()
        self.dbconnection.close()

Interacting with the database is simple. After creating the object, just use the execute method. int('port_example') raises ValueError; that argument has to be a port number. MySQLdb is not installed here, so this was not run.

db = Dbconnect()
db.dbcursor.execute('SELECT * FROM %s' % 'table_example')

The table name is interpolated with %, not passed as a parameter. A name taken from outside the program would be an SQL injection.

If you want to call a stored procedure, use the following syntax. Note that the parameters list is optional.

db = Dbconnect()
db.callproc('stored_procedure_name', [parameters] )

Dbconnect has no callproc method, so this raises AttributeError. The cursor method is db.dbcursor.callproc. [parameters] is also not valid as a stand-in unless that name exists.

After the query is done, you can access the results multiple ways. The cursor object is iterable. It can fetch all the results or be looped.

results = db.dbcursor.fetchall()
for individual_row in results:
    first_field = individual_row[0]

If you want a loop using directly the generator:

for individual_row in db.dbcursor:
    first_field = individual_row[0]

If you want to commit changes to the database:

db.commit_db()

If you want to close the cursor and the connection:

db.close_db()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents