python with sqlite3 code example
Example 1: install sqlite3 python
pip install pysqlite3
Example 2: sqlite3 python
import sqlite3 as lite
import sys
try:
con = lite.connect('products.db')
cur = con.cursor()
cur.execute("CREATE TABLE drinks(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Price REAL)")
cur.execute("CREATE TABLE fruits(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Price REAL)")
con.commit()
except e:
if con:
con.rollback()
print("Unexpected error %s:" % e.args[0])
sys.exit(1)
finally:
if con:
con.close()
Example 3: sqlite python connection
import sqlite3
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
sqlite_select_Query = "select sqlite_version();"
cursor.execute(sqlite_select_Query)
record = cursor.fetchall()
print("SQLite Database Version is: ", record)
cursor.close()
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("The SQLite connection is closed")
Example 4: how to install sqlite3 in python
$chmod +x sqlite.py
$./sqlite.py
Open database successfully