Last active
November 4, 2017 12:58
-
-
Save oiehot/70899f78fc5677b17846b65515c18279 to your computer and use it in GitHub Desktop.
Peewee ORM
This file contains hidden or 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
import sys | |
import peewee as pw # http://peewee.readthedocs.io/en/latest/peewee/api.html | |
# CONNECT | |
try: | |
db = pw.MySQLDatabase("database_name", host="192.168.0.10", port=3306, user="oiehot", passwd="1234") | |
db.connect() | |
except: | |
print('DB 접속 실패') | |
sys.exit() | |
class Person(pw.Model): | |
name = pw.CharField() | |
email = pw.TextField() | |
class Meta: | |
database = db | |
def __repr__(self): | |
return "<People(name:'%s', email:'%s')>" % (self.name, self.email) | |
# CREATE TABLE | |
try: | |
Person.create_table() | |
except: | |
pass | |
# INSERT | |
try: | |
a = Person(name='KD', email='[email protected]') | |
# a = Person.create(name='KD', email='[email protected]') | |
a.name = 'Kameron Deleon' | |
a.save() | |
except: | |
pass | |
# GET, DELETE | |
try: | |
a = Person.get(Person.name == 'Kameron Deleon') | |
a.delete_instance() | |
except: | |
pass | |
# GET OR CREATE | |
try: | |
a = Person.get_or_create(name='KD', email='[email protected]') | |
b = Person.get_or_create(name='Noelle Morales', email='[email protected]') | |
c = Person.get_or_create(name='Christian Maldonado', email='[email protected]') | |
d = Person.get_or_create(name='Taewoo Lee', email='[email protected]') | |
except: | |
pass | |
# SELECT WHERE | |
try: | |
ltw = Person.select().where(Person.name == 'Taewoo Lee').get() | |
print(ltw) | |
except: | |
pass | |
# FOR IN SELECT | |
try: | |
print('\nPERSON:\n') | |
for person in Person.select(): | |
print(person) | |
except: | |
pass | |
# SORT ORDER BY | |
try: | |
print('\nSORT ORDER BY:\n') | |
for person in Person.select().order_by(Person.name.desc()): | |
print(person) | |
except: | |
pass | |
# CLOSE | |
try: | |
db.close() | |
except: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment