Created
September 19, 2013 18:01
-
-
Save bbengfort/6627408 to your computer and use it in GitHub Desktop.
Database example.
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
import psycopg2 | |
HOST = "localhost" | |
PORT = "5432" | |
USER = "cobrain" | |
PASS = "" | |
NAME = "star_delta_0" | |
class Database(object): | |
def __init__(self, **kwargs): | |
self.host = kwargs.get('host', HOST) | |
self.port = kwargs.get('port', PORT) | |
self.user = kwargs.get('user', USER) | |
self.passwd = kwargs.get('password', PASS) | |
self.dbname = kwargs.get('dbname', NAME) | |
self._conn = None | |
@property | |
def connection(self): | |
if not self._conn: | |
self._conn = psycopg2.connect(database=self.dbname, | |
password=self.passwd, | |
host=self.host, | |
port=self.port, | |
user=self.user) | |
return self._conn | |
def execute(self, sql): | |
cursor = self.connection.cursor() | |
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE, cursor) | |
cursor.execute(sql) | |
return cursor | |
def close(self, cursor=None): | |
if cursor: cursor.close() | |
if self.connection: self.connection.close() | |
self._conn = None | |
if __name__ == "__main__": | |
db = Database() | |
cur = db.execute("SELECT * FROM vendor LIMIT 10;") | |
for row in cur.fetchall(): | |
print row | |
db.close(cur) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment