Guest User

Untitled

a guest
Sep 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. import psycopg2
  2.  
  3. from sqlalchemy import create_engine
  4. from sqlalchemy.ext.declarative import declarative_base
  5. from sqlalchemy import Column, Integer, String
  6. from sqlalchemy.orm import sessionmaker
  7.  
  8.  
  9. from passlib.hash import pbkdf2_sha256
  10.  
  11. engine = create_engine('postgresql://youruser:yourpass@192.168.1.103:5432/mydb')
  12. Base = declarative_base()
  13.  
  14.  
  15. Session = sessionmaker(bind=engine)
  16. session = Session()
  17.  
  18.  
  19. class MyStuff(Base):
  20.     __tablename__ = 'mytable'
  21.     id = Column(Integer, primary_key=True)
  22.     stuff = Column(String)
  23.  
  24.     def __repr__(self):
  25.         return 'MyStuff: %s, %s' % (self.id, self.stuff)
  26.  
  27.  
  28.  
  29. def add_w_orm(stuff_to_add):
  30.  
  31.     newstuff = MyStuff()
  32.     newstuff.stuff = stuff_to_add
  33.  
  34.     session.add(newstuff)
  35.     session.commit()
  36.  
  37.     print 'added'
  38.  
  39.  
  40. def query_w_orm():
  41.  
  42.     contents = session.query(MyStuff).all()
  43.  
  44.  
  45.  
  46.     print [i for i in contents]
  47.  
  48.  
  49. def func():
  50.     conn = psycopg2.connect(dbname='mydb', user='youruser', host='192.168.1.103', password='yourpass')
  51.  
  52.     cursor = conn.cursor()
  53.  
  54.     cursor.execute('SELECT * FROM mytable')
  55.  
  56.     print [i for i in cursor]
  57.  
  58.     # print [i for i in cursor]
  59.  
  60.     # try:
  61.     #     cursor.execute('INSERT INTO mytable(stuff) VALUES(%s)', ('masodik sor',))
  62.     #
  63.     #     cursor.execute('SELECT * FROM mytable')
  64.     #
  65.     #     conn.commit()
  66.     #
  67.     #     print [i for i in cursor]
  68.     #
  69.     # except Exception as e:
  70.     #     print str(e)
  71.  
  72.     cursor.close()
  73.     conn.close()
  74.  
  75.  
  76. if __name__ == '__main__':
  77.     func()
  78.     query_w_orm()
  79.  
  80.     add_w_orm('inserted with ORM')
  81.  
  82.     query_w_orm()
Add Comment
Please, Sign In to add comment