Using SQLite Database with Python
Download and install SQLite 3 in your machine from https://www.sqlite.org/download.html
Create a folder in some drive like D: as sqlite and drop sqlite3.exe file into it
Create a folder db into it
Open IDLE
Import the sqlite3 module and create the database
>>> import sqlite3
>>> sqlite3.connect("d:/sqlite/db/pythonsqlite.db")
Start the SQLite3, open the database connection and create required table. e.g.
CREATE TABLE book (
bookno integer PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
price real NOT NULL
);
import sqlite3
cn=sqlite3.connect("d:/sqlite/db/pythonsqlite.db")
cursor = cn.cursor()
while True:
bookno=int(input("Enter book no "))
title=input("Title ")
author=input("Author ")
price=float(input("Price "))
sql="insert into book values ({},'{}','{}',{})".format(bookno,title,author,price)
print(sql)
cursor.execute(sql)
cn.commit()
ans=input("Add more records [yes/no] ? ")
if(ans.lower()=="no"):
break
cn.close()
import sqlite3
cn=sqlite3.connect("d:/sqlite/db/pythonsqlite.db")
cursor = cn.cursor()
cursor.execute('select * from book')
r=cursor.fetchall()
for b in r:
print(b[0],b[1],b[2],b[3])
cn.close()
Create a folder in some drive like D: as sqlite and drop sqlite3.exe file into it
Create a folder db into it
Open IDLE
Import the sqlite3 module and create the database
>>> import sqlite3
>>> sqlite3.connect("d:/sqlite/db/pythonsqlite.db")
Start the SQLite3, open the database connection and create required table. e.g.
CREATE TABLE book (
bookno integer PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
price real NOT NULL
);
Save records into book table
#saving records into book tableimport sqlite3
cn=sqlite3.connect("d:/sqlite/db/pythonsqlite.db")
cursor = cn.cursor()
while True:
bookno=int(input("Enter book no "))
title=input("Title ")
author=input("Author ")
price=float(input("Price "))
sql="insert into book values ({},'{}','{}',{})".format(bookno,title,author,price)
print(sql)
cursor.execute(sql)
cn.commit()
ans=input("Add more records [yes/no] ? ")
if(ans.lower()=="no"):
break
cn.close()
Reading all records from book table
import sqlite3
cn=sqlite3.connect("d:/sqlite/db/pythonsqlite.db")
cursor = cn.cursor()
cursor.execute('select * from book')
r=cursor.fetchall()
for b in r:
print(b[0],b[1],b[2],b[3])
cn.close()


Comments
Post a Comment