Skip to content

Commit

Permalink
add
Browse files Browse the repository at this point in the history
  • Loading branch information
szabgab committed Aug 15, 2024
1 parent da1e723 commit 1d1b9c4
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 19 deletions.
8 changes: 8 additions & 0 deletions python/examples/sqlite/in_memory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import sqlite3

conn = sqlite3.connect(":memory:")
crs = conn.cursor()

# use the database here

conn.close()
45 changes: 27 additions & 18 deletions python/examples/sqlite/sql_create.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,34 @@
import sqlite3

conn = sqlite3.connect("companies.db")
crs = conn.cursor()

sql = '''
CREATE TABLE companies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCRCHAR(100) UNIQUE NOT NULL,
established INTEGER NOT NULL,
employees INTEGER DEFAULT 0
)
'''
def create_table(conn):
crs = conn.cursor()

try:
crs.execute(sql)
except sqlite3.OperationalError as err:
print(f'sqlite error: {err.args[0]}') # table companies already exists
print(f'remove companies.db to show how it works')
sql = '''
CREATE TABLE companies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCRCHAR(100) UNIQUE NOT NULL,
established INTEGER NOT NULL,
employees INTEGER DEFAULT 0
)
'''

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

conn.close()
conn.commit()

print('done')
def main():
conn = sqlite3.connect("companies.db")

create_table(conn)

conn.close()

print('done')

if __name__ == "__main__":
main()
16 changes: 15 additions & 1 deletion python/sqlite.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,30 @@
{id: sqlite3}
{i: sqlite}

* [sqlite3](http://docs.python.org/library/sqlite3.html)
* [SQLite](https://sqlite.org/) the most popular embedded relational database.
* [sqlite3](http://docs.python.org/library/sqlite3.html) - Python library to use SQLite.


## Connecting to SQLite database
{id: sqlite-connect}
{i: connect|sqlite}
{i: cursor|sqlite}

This connects to the database in the given file. If the file does not exist yet this will create the file and prepare it to hold
an SQLite database. No tables are created at this point and no data is inserted.

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

## Connecting to in-memory SQLite database
{id: sqlite-in-memory-connect}

We can also create in-memory database.

This is not persistent, but it can be useful to load some data into memory and then do fast SQL queries on
that database.

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


## Create TABLE in SQLite
{id: sqlite-create}
Expand Down

0 comments on commit 1d1b9c4

Please sign in to comment.