Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How we can store Python functions in a Sqlite table?

  • I have this code where an employee class and employee function have been created.
  • # employee.py
    class employee:
    def __init__(self, first, last, pay):
    self.first = first
    self.last = last
    self.pay = pay
    @property
    def email(self):
    return'{}{}@gmail.com'.format(self.first,self.last)
    @property
    def fullname(self):
    return'{}{}'.format(self.first,self.last)
    @property
    def __repr__(self):
    return"employee('{}','{}', {})".format(self.first,self.last)
    
    

  • How to use sqlite3 to store and manipulate data through a python function?


1 Answer
Rajendra Dharmkar

In the following code, we import sqlite3 module and establish a database connection. We create a table and then insert data and retrieve information from the sqlite3 database and close the connection finally.

#sqlitedemo.py
import sqlite3
from employee import employee
conn = sqlite3.connect('employee.db')
c=conn.cursor()
c.execute(‘’’CREATE TABLE employee(first text, last text, pay integer)’’’)
emp_1 = employee('John', 'Doe', 50000 )
emp_2 = employee('Jane', 'Doe', 60000)
emp_3 = employee('James', 'Dell', 80000)
c.execute(‘’’INSERT INTO employee VALUES(:first, :last,   :pay)’’’,{'first':emp_1.first, 'last':emp_1.last, 'pay':emp_1.pay})
c.execute(‘’’INSERT INTO employee VALUES(:first, :last, :pay)’’’,{'first':emp_2.first, 'last':emp_2.last, 'pay':emp_2.pay})
c.execute(‘’’INSERT INTO employee VALUES(:first, :last, :pay)’’’,{'first':emp_3.first, 'last':emp_3.last, 'pay':emp_3.pay})
c.execute("SELECT * FROM employee WHERE last ='Doe'")
print(c.fetchone())
print(c.fetchmany(2))
conn.commit()
conn.close()

OUTPUT

(u'James', u'Dell', 80000)
[(u'James', u'Dell', 80000), (u'James', u'Dell', 80000)]

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.