Skip to content

Commit

Permalink
add
Browse files Browse the repository at this point in the history
  • Loading branch information
szabgab committed Aug 14, 2024
1 parent b35bf28 commit b6f2926
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
54 changes: 54 additions & 0 deletions python/examples/sqlite/sql_autoincrement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import sqlite3


def insert(conn, crs, username):
sql = 'INSERT INTO people (username) VALUES (?)'
try:
crs.execute(sql, (username,))
except sqlite3.IntegrityError as err:
print('sqlite error: ', err.args[0])
conn.commit()


def list_rows(conn, crs):
sql = "SELECT * FROM people"
for id, username in crs.execute(sql):
print(f"{id} - {username}")


def create_table(conn, crs):
sql = '''
CREATE TABLE people (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCRCHAR(100) UNIQUE NOT NULL
);
'''

try:
crs.execute(sql)
except sqlite3.OperationalError as err:
print(f'sqlite error: {err.args[0]}') # table companies already exists
conn.commit()

def main():
conn = sqlite3.connect(":memory:")
crs = conn.cursor()
create_table(conn, crs)

insert(conn, crs, "rachel")
list_rows(conn, crs)

insert(conn, crs, "joey")
list_rows(conn, crs)

insert(conn, crs, "monica")
list_rows(conn, crs)

insert(conn, crs, "monica")
list_rows(conn, crs)

conn.close()
print('done')


main()
8 changes: 7 additions & 1 deletion python/sqlite.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,15 @@ If the result set might be empty, then the fetchone might return None. Check for

![](examples/sqlite/sql_update.py)


## A counter
{id: sqlite-counter}

![](examples/sqlite/counter.py)

## SQLite in-memory AUTOINCREMENT
{id: sqlite-in-memory-autoincrement}
{i: AUTOINCREMENT}
{i: :memory:}

![](examples/sqlite/sql_autoincrement.py)

0 comments on commit b6f2926

Please sign in to comment.