· 6 years ago · Dec 06, 2019, 01:20 PM
1import sqlite3
2
3def create_table(db_name,table_name,sql):
4 with sqlite3.connect(db_name) as db:
5 cursor = db.cursor()
6 cursor.execute("select name from sqlite_master where name=?",(table_name,))
7 result = cursor.fetchall()
8 keep_table = True
9 if len(result) == 1:
10 response = input("the table {0} already exists, do you want to recreate it (y/n) \n >".format(table_name))
11 if response == "y":
12 keep_table = False
13 print ("The table {0} will be recreated - all existing data will be lost".format(table_name))
14 cursor.execute("drop table if exists {0}".format(table_name))
15 db.commit()
16 else:
17 print ("The existing table was kept")
18 else:
19 keep_table = False
20 if not keep_table:
21 cursor.execute(sql)
22 db.commit()
23
24if __name__ == "__main__":
25 db_name = "coffee_shop.db"
26 sql = """create table Product
27 (ProductID integer,
28 Name text,
29 Price real,
30 primary key(ProductID))"""
31 create_table(db_name,"Product",sql)