Created
September 8, 2015 01:54
-
-
Save sugiana/f95c395d3f1fb5489a86 to your computer and use it in GitHub Desktop.
INSERT or UPDATE use SQLAlchemy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import create_engine | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy import Column, Integer, String | |
from sqlalchemy.orm import sessionmaker | |
Base = declarative_base() | |
class User(Base): | |
__tablename__ = 'users' | |
id = Column(Integer, primary_key=True) | |
name = Column(String(30), unique=True, nullable=False) | |
fullname = Column(String(30), nullable=False) | |
password = Column(String(30)) | |
db_url = 'postgresql://sugiana:a@localhost/test' | |
engine = create_engine(db_url) | |
Base.metadata.create_all(engine) # Create Table | |
session_factory = sessionmaker(bind=engine) | |
DBSession = session_factory() | |
daftar_user = [ | |
['yohan', 'Yohan Kurniawan'], | |
['sugiana', 'Owo Sugiana'], | |
] | |
for name, fullname in daftar_user: | |
u = DBSession.query(User).filter_by(name=name).first() | |
if not u: | |
u = User(name=name) # INSERT | |
u.fullname = fullname | |
DBSession.add(u) | |
DBSession.flush() # Send to db server | |
DBSession.commit() # Save permanent |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment