Python and sqlite
Source code for creating a table in a database and accessing data:
import sqlite3
con=sqlite3.connect("school.db")
cur=con.cursor()
con.execute("""CREATE TABLE IF NOT EXISTS student(
roll INT(3),
name VARCHAR(40));""")
for i in range(1,4):
r=int(input("Enter a roll no.:"))
n=input("Enter a name:")
con.execute("INSERT INTO student VALUES(?,?)",(r,n))
con.commit()
cur.execute("SELECT * FROM student")
rs=cur.fetchall()
for i in rs:
print(i)
con.close()
con=sqlite3.connect("school.db")
cur=con.cursor()
con.execute("""CREATE TABLE IF NOT EXISTS student(
roll INT(3),
name VARCHAR(40));""")
for i in range(1,4):
r=int(input("Enter a roll no.:"))
n=input("Enter a name:")
con.execute("INSERT INTO student VALUES(?,?)",(r,n))
con.commit()
cur.execute("SELECT * FROM student")
rs=cur.fetchall()
for i in rs:
print(i)
con.close()
Source code for modifying a record in the table:
import sqlite3
con=sqlite3.connect("school.db")
cur=con.cursor()
r=int(input("Enter the roll no. to modify:"))
n=input("Enter new name:")
con.execute("UPDATE student SET name=? WHERE roll=?;",(n,r))
con.commit()
cur.execute("SELECT * FROM student")
rs=cur.fetchall()
for i in rs:
print(i)
con.close()
import sqlite3
con=sqlite3.connect("school.db")
cur=con.cursor()
r=int(input("Enter the roll no. to delete:"))
print(con.execute("DELETE FROM student WHERE roll=?;",(r,)))
con.commit()
cur.execute("SELECT * FROM student")
rs=cur.fetchall()
for i in rs:
print(i)
con.close()
con=sqlite3.connect("school.db")
cur=con.cursor()
r=int(input("Enter the roll no. to modify:"))
n=input("Enter new name:")
con.execute("UPDATE student SET name=? WHERE roll=?;",(n,r))
con.commit()
cur.execute("SELECT * FROM student")
rs=cur.fetchall()
for i in rs:
print(i)
con.close()
Source code for removing a record in the table:
import sqlite3
con=sqlite3.connect("school.db")
cur=con.cursor()
r=int(input("Enter the roll no. to delete:"))
print(con.execute("DELETE FROM student WHERE roll=?;",(r,)))
con.commit()
cur.execute("SELECT * FROM student")
rs=cur.fetchall()
for i in rs:
print(i)
con.close()
No comments:
Post a Comment