-
Notifications
You must be signed in to change notification settings - Fork 0
/
DB_ORM_Testing.py
60 lines (45 loc) · 1.32 KB
/
DB_ORM_Testing.py
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
54
55
56
57
58
59
import os
import sqlalchemy
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
sql = 'postgresql'
ip = os.getenv('DB_IP_PORT')
username = os.getenv('DB_USER_NAME')
password = os.getenv('DB_PASSWORD')
dbname = os.getenv('DB_NAME')
db_url = f'{sql}://{username}:{password}@{ip}/{dbname}'
engine = sqlalchemy.create_engine(db_url)
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
# Create the database schema
Base.metadata.create_all(engine)
# Create a session to interact with the database
Session = sessionmaker(engine)
session = Session()
# CREATE(INSERT)
new_user = User(name = 'John', age = 30 )
session.add(new_user)
session.commit()
# READ(SELECT)
user = session.query(User).filter_by(name = 'John').first()
print(f'UserID: {user.id}, Name: {user.name}, Age: {user.age}')
# UPDATE
user.age = 35
session.commit()
print(f'UserID: {user.id}, Name: {user.name}, Age: {user.age}')
#DELETE(DROP)
session.delete(user)
session.commit()
#Close Session
session.close()
try:
connect = engine.connect()
print('Connected To PostgreSQL Database')
connect.close()
except Exception as e:
print(f'Connect fail: {e}')