Web Programming with Python: Inserting Dynamic Data

Welcome to this tutorial on inserting dynamic data. In real time scenario data is always entered dynamically and that’s why programs are made. There is no point entering hardcoded data. To explain the concept we will create a function which will prompt user to insert values and those values will be inserted into the data base.

This is the code that we had written for inserting hardcoded data:

Import sqlite3
conn=sqlite3.connnect(‘tutorial.db’)
c=conn.cursor()
def create_table():
       c.execute(“CREATE TABLE example (Language VARCHAR, Version REAL, skill TEXT”)

def enter_data():
      c.execute(“INSERT INTO example VALUES(‘Python’, 2.7, ‘Beginner’)”)
      c.execute(“INSERT INTO example VALUES(‘Python’, 3.3, ‘Intermediate’)”)
      c.execute(“INSERT INTO example VALUES(‘Python’, 3.4, ‘Expert’)”)
      conn.commit()
enter_data()

We now define a new function:

def enter_dynamic_data():
      lang=input(“What Language?”)
      version=float(Input(“What Version?”)
      skill=input(“What skill level?”)
      c.execute(“INSERT INTO example(Language, Version,skill)  VALUES(?,?,?)”,(lang, version,skill))
      conn.commit()

So, the final code looks like this:

Import sqlite3
conn=sqlite3.connnect(‘tutorial.db’)
c=conn.cursor()
def create_table():
       c.execute(“CREATE TABLE example (Language VARCHAR, Version REAL, skill TEXT”)

def enter_data():
      c.execute(“INSERT INTO example VALUES(‘Python’, 2.7, ‘Beginner’)”)
      c.execute(“INSERT INTO example VALUES(‘Python’, 3.3, ‘Intermediate’)”)
      c.execute(“INSERT INTO example VALUES(‘Python’, 3.4, ‘Expert’)”)
      conn.commit()

def enter_dynamic_data():
      lang=input(“What Language?”)
      version=float(Input(“What Version?”)
      skill=input(“What skill level?”)
      c.execute(“INSERT INTO example(Language, Version,skill)  VALUES(?,?,?)”,(lang, version,skill))
      conn.commit()
enter_dynamic_data()
So, when you execute this program you will be prompted to feed in the values for Language, version and skill level. Your inputs will be inserted in the database. But how would you know if the values have been inserted in the database? For that you would have to move on to the next tutorial on “Reading Data”

Online Technology Courses Stone River eLearning

GET YOUR FREE PYTHON EBOOK!

Comments