-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
55 lines (36 loc) · 2.1 KB
/
Copy pathapp.py
File metadata and controls
55 lines (36 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# pip install psycopg2-binary sqlalchemy
# NOTE: DO NOT USE python:alpine IMAGE , it doesnt have the required packages for psycopg2
# use python:3.10 for example
from sqlalchemy import create_engine , text
# create engine
engine = create_engine("postgresql+psycopg2://<user(postgres)>:<password>@<hostname/ip>:5432/<existing_db_name(postgres)>")
# connect to database with the engine
# IMP: enable autocommit
db = engine.connect().execution_options(isolation_level="AUTOCOMMIT")
# list all databases
db.execute(text("SELECT datname FROM pg_database WHERE datistemplate = false")).fetchall()
database_names = [row[0] for row in re]
# check if db exists
name = "ali"
db.execute(text(f"SELECT datname FROM pg_database WHERE datname = '{name}' ")).fetchone()
# create database
db.execute(text("create database database"))
# list tables
db.execute(text(f"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'")).fetchall()
# check if table exists
from sqlalchemy import inspect
inspect(engine).has_table("<table_name>") #==> true or false
# create table with autoincrement column and primary key
db.execute(text(f"create table test (id serial primary key , name varchar(255))"))
## insert data into table
query = text(f"insert into test (name) values (:name)")
param = {"name": "alireza"}
db.execute(query,param)
# create uuid
uuid = db.execute(text("select uuid()")).fetchall()
print(uuid[0][0])
## select from table where name = alireza
name = "alireza"
db.execute(text(f"select * from test where name = \'{name}\'")).fetchall() #==> 2d array
## CLOSE THE CONNECTION AFTER YOU ARE DONE
db.close()