Articles


Accessing MySQL database from Python script using MySQLdb



Posted bynitheesh,31st Aug 2016

The first thing you need to do is to 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.dbconection = MySQLdb.connect(host='host_example',
                       port=int('port_example'),
                       user='user_example',
                       passwd='pass_example',
                       db='schema_example')
    self.dbcursor = self.dbconection.cursor()

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

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