sqlite database python code example
Example 1: 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 2: create sqlite database python
import sqlite3
conn = sqlite3.connect('TestDB.db')
c = conn.cursor()
c.execute('''CREATE TABLE CLIENTS
([generated_id] INTEGER PRIMARY KEY,[Client_Name] text, [Country_ID] integer, [Date] date)''')
c.execute('''CREATE TABLE COUNTRY
([generated_id] INTEGER PRIMARY KEY,[Country_ID] integer, [Country_Name] text)''')
c.execute('''CREATE TABLE DAILY_STATUS
([Client_Name] text, [Country_Name] text, [Date] date)''')
conn.commit()
Example 3: create sqlite database python
import sqlite3
import pandas as pd
from pandas import DataFrame
conn = sqlite3.connect('TestDB.db')
c = conn.cursor()
read_clients = pd.read_csv (r'C:\Users\Ron\Desktop\Client\Client_14-JAN-2019.csv')
read_clients.to_sql('CLIENTS', conn, if_exists='append', index = False)
read_country = pd.read_csv (r'C:\Users\Ron\Desktop\Client\Country_14-JAN-2019.csv')
read_country.to_sql('COUNTRY', conn, if_exists='replace', index = False)
c.execute('''
INSERT INTO DAILY_STATUS (Client_Name,Country_Name,Date)
SELECT DISTINCT clt.Client_Name, ctr.Country_Name, clt.Date
FROM CLIENTS clt
LEFT JOIN COUNTRY ctr ON clt.Country_ID = ctr.Country_ID
''')
c.execute('''
SELECT DISTINCT *
FROM DAILY_STATUS
WHERE Date = (SELECT max(Date) FROM DAILY_STATUS)
''')
df = DataFrame(c.fetchall(), columns=['Client_Name','Country_Name','Date'])
print (df)
df.to_sql('DAILY_STATUS', conn, if_exists='append', index = False)