1. Computing

Inserting Data Into a MySQL Database

By

5 of 8

A Touch of Class

As I said earlier, it is best to define a class in order to access a database. Here I again define a class called Table which allows me to insert data (additem). Unlike the example code for reading from the database, we here do not need to know the length of the database to read through all of its records.

The following code presupposes a table with two columns in it: the first field is the record identifier and the second is the record content.

 class Table: 
      def __init__(self, db, name): 
           self.db = db 
           self.name = name
           self.dbc = self.db.cursor() 
 
      def additem(self, item): 
           sql = "INSERT INTO " + self.name + " VALUES(" + id + ", " + item + ")"
           self.dbc.execute(sql) 
           return
 
 

Rather than define the statement within the argument of self.dbc.execute, I here define it and then call it as an argument. If you have trouble with your script and it is giving unexpected output, try to define the variables separately from the arguments and then print them out. This will give you insight into the flow of the program and enable you to see where things are going awry.

  1. About.com
  2. Computing
  3. Python
  4. Database Programming
  5. Python and MySQL - Inserting Python Data Into a MySQL Database - A Python Class for MySQL INSERTs

©2014 About.com. All rights reserved.