1import sqlite3
2conn = sqlite3.connect('example.db')
3c = conn.cursor()
4
5# Create table
6c.execute('''CREATE TABLE stocks
7 (date text, trans text, symbol text, qty real, price real)''')
8
9# Insert a row of data
10c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
11
12# Save (commit) the changes
13conn.commit()
14
15# We can also close the connection if we are done with it.
16# Just be sure any changes have been committed or they will be lost.
17conn.close()
1import sqlite3
2
3# Create database
4conn = sqlite3.connect('tablename.db')
5c = conn.cursor()
6c.execute('''CREATE TABLE tablename(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, number REAL)''')
7conn.commit()
8conn.close()
9
10# Insert Values
11conn = sqlite3.connect('tablename.db')
12c = conn.cursor()
13c.execute("INSERT INTO tablename VALUES (?, ?)", (name, number))
14conn.commit()
15conn.close()
16
17# Read Values
18conn = sqlite3.connect('tablename.db')
19c = conn.cursor()
20
21for row in c.execute('SELECT * FROM tablename'):
22 print(row)
23
24number = [row[2] for row in c.execute('SELECT * FROM tablename')]
25conn.close()
1import sqlite3
2
3con = sqlite3.connect(":memory:")
4con.isolation_level = None
5cur = con.cursor()
6
7buffer = ""
8
9print("Enter your SQL commands to execute in sqlite3.")
10print("Enter a blank line to exit.")
11
12while True:
13 line = input()
14 if line == "":
15 break
16 buffer += line
17 if sqlite3.complete_statement(buffer):
18 try:
19 buffer = buffer.strip()
20 cur.execute(buffer)
21
22 if buffer.lstrip().upper().startswith("SELECT"):
23 print(cur.fetchall())
24 except sqlite3.Error as e:
25 print("An error occurred:", e.args[0])
26 buffer = ""
27
28con.close()