Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

DATABASE CONNECTIVITY

1) Create a table and insert values to it.

import sqlite3

connection = sqlite3.connect("myTable.db")

crsr = connection.cursor()

sql_command = """CREATE TABLE emp (


staff_number INTEGER PRIMARY KEY,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE);"""

crsr.execute(sql_command)

sql_command = """INSERT INTO emp VALUES (23, "Rishabh",


"Bansal", "M", "2014-03-28");"""
crsr.execute(sql_command)

sql_command = """INSERT INTO emp VALUES (1, "Bill", "Gates",


"M", "1980-10-28");"""
crsr.execute(sql_command)

connection.commit()

connection.close()
2) To fetch all the data from database

import sqlite3

connection = sqlite3.connect("myTable.db")

crsr = connection.cursor()

crsr.execute("SELECT * FROM emp")

ans= crsr.fetchall()

for i in ans:
print(i)

3) Update command:

import sqlite3

conn = sqlite3.connect(myTable.db')

conn.execute("UPDATE emp SET fname = 'Sam' where lname =


‘Bansal’")
conn.commit()

cursor = conn.execute("SELECT * FROM emp ")


for row in cursor:
print row,
conn.close()
4) Delete command:

import sqlite3

conn = sqlite3.connect(myTable.db')

conn.execute("DELETE from emp where lname = ‘Bansal’")


conn.commit()

cursor = conn.execute("SELECT * FROM emp")


for row in cursor:
print row,

conn.close()

You might also like