1 # -*- coding: latin-1; -*-
3 # PgWorksheet - PostgreSQL Front End
4 # http://pgworksheet.projects.postgresql.org/
6 # Copyright © 2004-2005 Henri Michelon & CML http://www.e-cml.org/
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details (read LICENSE.txt).
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 # $Id: DBConnection.py,v 1.20 2005/03/01 16:09:57 hmichelon Exp $
26 #from mx import DateTime
27 from pyPgSQL
import libpq
28 from pyPgSQL
import PgSQL
30 class ConnectionParameter
:
31 def __init__(self
, name
="", user
="", password
="", db
="", local
=False, host
="", port
="5432"):
35 self
.password
= password
45 if (self
.host
is not None):
50 if (self
.port
is not None):
51 dsn
= dsn
+ str(self
.port
)
55 if (self
.db
is not None):
60 if (self
.user
is not None):
64 if (self
.password
is not None):
65 dsn
= dsn
+ self
.password
69 print "NAME=%s : user=%s, password=%s, db=%s, local=%s, host=%s, port=%s"%(self
.name
, self
.user
, self
.password
, self
.db
, self
.local
, self
.host
, self
.port
)
72 DatabaseError
= libpq
.DatabaseError
75 """Database connection/deconnection and query execution"""
80 def connect(self
, connectionParameter
):
81 """Try to connect to a database"""
82 self
.connectionParameter
= connectionParameter
83 #self.db = MyPgSQL.connect(dsn) #delete see svn history for MyPgSQL.py. i dunno why this was necessary
84 self
.db
= PgSQL
.connect(connectionParameter
.get_dsn())
85 self
.db
.autocommit
= 1
90 if (self
.is_connected()):
91 v
= string
.split(str(self
.db
.version
), ',')
97 """Execute a query and return the corresponding DB-API cursor."""
98 if not self
.is_connected() : return None
99 cursor
= self
.db
.cursor()
101 cursor
.execute("SET CLIENT_ENCODING TO 'UTF-8'")
103 except libpq
.OperationalError
, msg
:
105 return { 'error' : str(msg
), 'notices' : self
.db
.notices
}
106 return { 'cursor' : cursor
, 'notices' : self
.db
.notices
}
110 if not self
.is_connected() : return
114 def is_connected(self
):
115 return (self
.db
!= None)
118 def disconnect(self
):
119 if not self
.is_connected() : return