In: Computer Science
In Java Please!!!
6.22 LAB: Python and sqlite basics Write a Python program that connects to a sqlite database. Create a table called Horses with the following fields: id (integer): a primary key and not null name (text) breed (text) height (real) birthday (text) Next, insert the following data row into the Horses table: id: 1 name: 'Babe' breed: 'Quarter Horse' height: 15.3 birthday: '2015-02-10' Output all records from the Horses table. Ex: With the above row inserted, the output should be: All Horses: (1, 'Babe', 'Quarter Horse', 15.3, '2015-02-10')
Answer:-
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(":memory:")
return conn
except Error as e:
print(e)
# query to create the table
table_sql = """
CREATE TABLE Horses (
id integer PRIMARY KEY NOT NULL,
name text,
breed text,
height real,
birthday text
);
"""
# query to insert data into the table
ins_sql = """INSERT INTO Horses VALUES(1,'Babe','Quarter Horse',15.3,'2015-02-10'); """
# query to fetch all data from the table
fetch_sql = """SELECT * FROM Horses;"""
# creating db connection
conn = create_connection(None)
# fetching a cursor from the connection
c = conn.cursor()
# executing statement to create table
c.execute(table_sql)
# executing statement to insert data into the table
c.execute(ins_sql)
# executing statement to fetch data from the table
c.execute(fetch_sql)
# fetching rows retrieved by last query
rows = c.fetchall()
print("All Horses:")
# looping and printing each row returned.
for row in rows:
print(row)