1702378369

Lets create a short tutorial on how to connect, create a table and insert data in SQlite with Python


## Connecting to SQlite database ```py import sqlite3 cone = sqlite3.connect("sampleardes.db") c = cone.cursor() # user the database here cone.close() ``` ## Create table in SQLite execute and commit ```py import sqlite3 cone = sqlite3.connect("sampleardes.db") c = conn.cursor() try: c.execute(\CREATE TABLE companies ID PRIMARY KEY, name VARCHAR(100) UNIQUE NOT NULL, employees INTEGER DEFAULT 0\) except sqlite3.OperationalError as e: print("sqlite error:", e.args[0]) # table companies already exists conn.commit() conn.close() print("done") ``` ## Insert data into SQLite database ```py import sqlite3 conn = sqlite3.connect("sample.db") c = conn.cursor() my_company = "Acme" try: c.execute(\INSERT INTO companies (name) VALUES(?)\, (my_company,)) except sqlite3.IntegrityError as e: print("sqlite error: ", e.arg[0]) # column name is not unique conn.commit() companies = [ ("Foo", 12), ("Bar", 7), ("Moo", 99), ] try: sql = \INSERT INTO companies (name, employees) VALUES (?,?)\\r c.executemany(sql, companies) except sqlite3.IntegrityError as e: print("sqlite error: ", e.args[0]) # column name is not unique conn.commit() conn.close() print("done") ``` UPDATE works quite similar, but it might have a WHERE clause.

(1) Comments
amargo85
amargo85
0

what I'm enjoying most about the site is the way the codes are presented. good organization and very efficient content