-
Notifications
You must be signed in to change notification settings - Fork 1
/
sqlalchemy_python
50 lines (38 loc) · 1.13 KB
/
sqlalchemy_python
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
# Import required modules
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker, declarative_base
from random import randint
# Create database connection
engine = create_engine('postgresql://username:password@localhost/mydatabase')
Session = sessionmaker(bind=engine)
Base = declarative_base()
# Define models
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
def __init__(self, name, email):
self.name = name
self.email = email
# Create tables
Base.metadata.create_all(engine)
# Insert data
session = Session()
user1 = User(name='John Doe', email='[email protected]')
session.add(user1)
session.commit()
# Retrieve data
users = session.query(User).all()
for user in users:
print(user.name, user.email)
# Update data
user = session.query(User).filter_by(name='John Doe').first()
user.email = '[email protected]'
session.commit()
# Delete data
user = session.query(User).filter_by(name='John Doe').first()
session.delete(user)
session.commit()
# Close session
session.close()