• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pyPgSQL.PgSQL类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyPgSQL.PgSQL的典型用法代码示例。如果您正苦于以下问题:Python PgSQL类的具体用法?Python PgSQL怎么用?Python PgSQL使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了PgSQL类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

 def __init__(self, connectArgs):
     connectArgs = string.split(connectArgs,':')
     host = None
     if connectArgs and connectArgs[0]: #if host is there
         if '|' in connectArgs[0]: #if specified port
             host = connectArgs[0].replace('|', ':')
             
     if connectArgs and connectArgs[-1] == 'verbose':
         self.verbose = 1
         connectArgs = connectArgs[:-1]
     else:
         self.verbose=0
     if connectArgs and connectArgs[-1] == 'cache':
         self.useCacheMod = 1
         connectArgs = string.join(connectArgs[:-1], ':')
     else:
         connectArgs = string.join(connectArgs, ':')
         self.useCacheMod =0
     
     self.connectArgs = connectArgs
     if self.useCacheMod:
         from PyPgSQLcache import getConnection
         self.conn = getConnection(connectArgs)
     else:
         if host is not None:
             self.conn = PgSQL.connect(connectArgs, host = host)
         else:
             self.conn = PgSQL.connect(connectArgs)
     self.bindVariables = 0
开发者ID:BackupTheBerlios,项目名称:skunkweb-svn,代码行数:29,代码来源:pypgsqlconn.py


示例2: __init__

    def __init__(self, db_name, db_host):
        from pyPgSQL import PgSQL
	if len(db_host) == 0:
	    db_user = pwd.getpwuid(os.geteuid())[0]
            self.connection = PgSQL.connect(database=db_name, user=db_user)
        else:
            self.connection = PgSQL.connect(database=db_name, host=db_host)
        self.connection.autocommit = AUTOCOMMIT
开发者ID:Fat-Zer,项目名称:LDP,代码行数:8,代码来源:Database.py


示例3: connect

 def connect(self):
     """ Connect to the database"""
     if len(self.dbhost):
         self.dbh = PgSQL.connect(database=self.dbname, host=self.dbhost, 
                                  user=self.dbuser, password=self.dbpass,
                                  client_encoding="utf-8",
                                  unicode_results=1)
     else:
         self.dbh = PgSQL.connect(database=self.dbname, 
                                  user=self.dbuser, 
                                  password=self.dbpass,
                                  client_encoding="utf-8",
                                  unicode_results=1)
开发者ID:codingforfun,项目名称:pymagellan,代码行数:13,代码来源:sqlbuilder.py


示例4: connect_by_uri

def connect_by_uri(uri):
    """General URI syntax:

    postgres://user:[email protected]:port/database?opt1=val1&opt2=val2...

    where opt_n is in the list of options supported by PostGreSQL:

        host,user,password,port,database,client_encoding,unicode_results

    NOTE: the authority and the path parts of the URI have precedence
    over the query part, if an argument is given in both.

    Descriptions of options:
        file:///usr/lib/python?.?/site-packages/pyPgSQL/PgSQL.py

    """
    puri = urisup.uri_help_split(uri)
    params = __dict_from_query(puri[QUERY])
    if puri[AUTHORITY]:
        user, password, host, port = puri[AUTHORITY]
        if user:
            params['user'] = user
        if password:
            params['password'] = password
        if host:
            params['host'] = host
        if port:
            params['port'] = port
    if puri[PATH]:
        params['database'] = puri[PATH]
        if params['database'] and params['database'][0] == '/':
            params['database'] = params['database'][1:]
    __apply_types(params, __typemap)
    return PgSQL.connect(**params)
开发者ID:Eyepea,项目名称:xivo-gallifrey,代码行数:34,代码来源:backpg.py


示例5: launchCfgGenerator

	def launchCfgGenerator(self):
		Logger.ZEyeLogger().write("MRTG configuration discovery started")
		starttime = datetime.datetime.now()
		try:
			pgsqlCon = PgSQL.connect(host=netdiscoCfg.pgHost,user=netdiscoCfg.pgUser,password=netdiscoCfg.pgPwd,database=netdiscoCfg.pgDB)
			pgcursor = pgsqlCon.cursor()
			pgcursor.execute("SELECT ip,name FROM device ORDER BY ip")
			try:
				pgres = pgcursor.fetchall()
				for idx in pgres:
					pgcursor2 = pgsqlCon.cursor()
					pgcursor2.execute("SELECT snmpro FROM z_eye_snmp_cache where device = '%s'" % idx[1])
					pgres2 = pgcursor2.fetchone()
			
					devip = idx[0]
					devname = idx[1]
					if pgres2:
						devcom = pgres2[0]
					else:
						devcom = self.defaultSNMPRO
					thread.start_new_thread(self.fetchMRTGInfos,(devip,devname,devcom))
			except StandardError, e:
				Logger.ZEyeLogger().write("MRTG-Config-Discovery: FATAL %s" % e)
				return
				
		except PgSQL.Error, e:
			Logger.ZEyeLogger().write("MRTG-Config-Discovery: FATAL PgSQL %s" % e)
			sys.exit(1);	
开发者ID:jp-morvan,项目名称:Z-Eye,代码行数:28,代码来源:MRTGCfgDiscoverer.py


示例6: configAndTryConnect

	def configAndTryConnect (self, dbType, dbHost, dbPort, dbName, dbLogin, dbPwd):
		if dbType != "my" and dbType != "pg":
			return False
	
		try:
			if dbType == "pg":
				self.dbConn = PgSQL.connect(host=dbHost,user=dbLogin,password=dbPwd,database=dbName)
				if self.dbConn == None:
					return False
					
				self.dbCursor = self.dbConn.cursor()
				if self.dbCursor == None:
					self.dbConn.close()
					return False
				
			elif dbType == "my":
				self.dbConn =  pymysql.connect(host=dbHost, port=dbPort, user=dbLogin, passwd=dbPwd, db=dbName)
				if self.dbConn == None:
					return False
				
				self.dbCursor = self.dbConn.cursor()
				if self.dbCursor == None:
					self.dbConn.close()
					return False

			else:
				self.logger.warn("Database '%s' not supported" % dbType)
				return False
		except Exception, e:
			self.logger.error("DBMgr: connection to DB %s:%s/%s failed: %s" % (dbHost,dbPort,dbName,e))
			return False
开发者ID:nerzhul,项目名称:Z-Eye,代码行数:31,代码来源:DatabaseManager.py


示例7: __init__

	def __init__(self, dsn = None, dbapi = None):

		if dsn == None:
			dsn ="localhost:gnumed:gm-dbo:pg"

		if dbapi == None:
			use_pgdb = '-pgdb' in sys.argv

			try:
				from pyPgSQL import PgSQL
				dbapi = PgSQL
				l = dsn.split(':')
				if len(l) == 4:
					l = [l[0]] + [''] + l[1:]
					dsn = ':'.join(l)

			except:
				print sys.exc_info()[0], sys.exc_info()[1]
				use_pgdb = 1

			if use_pgdb:

				import pgdb
				dbapi = pgdb


		self.dsn = dsn
		try:
			self.conn = dbapi.connect(dsn)
			return
		except:
			print sys.exc_info()[0], sys.exc_info()[1]

		self.conn = PgSQL.connect(dsn)
开发者ID:ncqgm,项目名称:gnumed,代码行数:34,代码来源:PlainConnectionProvider.py


示例8: __init__

 def __init__(self, in_userid):
     self.__tasks = []
     self.db = PgSQL.connect (database="jackdesert_groove", user="jackdesert_groove", password="123567")
     self.cur = self.db.cursor()
     # self.reset_table(self.cur)
     self.__userid = int(in_userid)
     self.__utcoffset = int(self.retrieve_utcoffset())
开发者ID:jackdesert,项目名称:groovetask,代码行数:7,代码来源:Menu.py


示例9: _connect

def _connect(host="", database="", user="", password=""):
    """Opens a connection to the database.

    Normally, this function does not have to be called, because the other
    functions of this module connect to the database automatically.  If invoked
    without parameters, it uses the default connection parameters for the DES
    database.  If, for some reason, you need to connect to a different database
    or use different credentials, you can invoke this function with the desired
    parameters. Further calls of functions from this module will then use that
    connection.

    """
    global _connection
    # Use the default values for the connection, if the parameters are not given
    if host == "":
        host = _HOST
    if database == "":
        database = _DATABASE
    if user == "":
        user = _USER
    if password == "":
        password = _PASSWORD
    # Make a connection to the database and check to see if it succeeded.
    try:
        _connection = PgSQL.connect(host=host, database=database, user=user,\
                                    password=password)
    except PgSQL.Error, msg:
        errstr = "Connection to database '%s' failed\n%s" % (_DATABASE, msg)
        raise Error(errstr.strip())
开发者ID:des-testbed,项目名称:des_chan,代码行数:29,代码来源:des_db.py


示例10: launchCfgGenerator

	def launchCfgGenerator(self):
		while self.SNMPcc.isRunning():
			self.logDebug("SNMP community caching is running, waiting 10 seconds")
			time.sleep(10)

		self.launchMsg()
		try:
			pgsqlCon = PgSQL.connect(host=zConfig.pgHost,user=zConfig.pgUser,password=zConfig.pgPwd,database=zConfig.pgDB)
			pgcursor = pgsqlCon.cursor()
			pgcursor.execute("SELECT ip,name FROM device ORDER BY ip")
			try:
				pgres = pgcursor.fetchall()
				for idx in pgres:
					devip = idx[0]
					devname = idx[1]
					devcom = self.SNMPcc.getReadCommunity(devname)

					# Only launch process if SNMP cache is ok
					if devcom == None:
						self.logError("No read community found for %s" % devname)
					else:
						thread.start_new_thread(self.fetchMRTGInfos,(devip,devname,devcom))
			except StandardError, e:
				self.logCritical(e)
				return
				
		except PgSQL.Error, e:
			self.logCritical("FATAL PgSQL %s" % e)
			sys.exit(1);	
开发者ID:nerzhul,项目名称:Z-Eye,代码行数:29,代码来源:zMRTG.py


示例11: main

def main():
    db = PgSQL.connect(database='casemgr')
    curs = db.cursor()
    curs.execute('create index wqdesc on workqueues (description);')
    curs.execute('select unit_id from units where unit_id not in (select unit_id from workqueues where unit_id is not null)')
    unit_ids = fetchids(curs)
    curs.execute('select user_id from users where user_id not in (select user_id from workqueues where user_id is not null)')
    user_ids = fetchids(curs)
    print 'Units %d, Users %d' % (len(unit_ids), len(user_ids))
    # Create workqueues
    many(curs, 'insert wq', 'insert into workqueues (name,description, unit_id, user_id) values (%s,%s,%s,%s)', wq_rows(unit_ids, user_ids))
    # Find shared queues
    curs.execute("select queue_id from workqueues where unit_id is null and user_id is null and description = 'X'")
    shared_queues = fetchids(curs)
    # Add members to shared queues
    print 'Shared queues %s' % len(shared_queues)
    many(curs, 'insert wqm', 'insert into workqueue_members (queue_id, unit_id, user_id) values (%s,%s,%s)', wqm_rows(shared_queues, unit_ids, user_ids))
    # Create tasks
    curs.execute("select master_id from cases")
    case_ids = fetchids(curs)
    curs.execute("select queue_id from workqueues where description='X'")
    queue_ids = fetchids(curs)
    many(curs, 'insert tasks', 'insert into tasks (queue_id, task_description, case_id) values (%s, %s, %s)', task_rows(case_ids, queue_ids))
    curs.execute('drop index wqdesc;')
    db.commit()
开发者ID:timchurches,项目名称:NetEpi-Collection,代码行数:25,代码来源:populate_tasks.py


示例12: getConnection

def getConnection(connUser):
    """
    Returns a database connection as defined by 
    connUser. If this module already has an open
    connection for connUser, it returns it; otherwise,
    it creates a new connection, stores it, and returns it.
    """

    if not _users.has_key(connUser):
        raise SkunkStandardError, "user %s is not initialized" % (connUser)

    connectParams = _users[connUser]

    if not _connections.has_key(connectParams):
        try:
            connectArgs = string.split(connectParams, ":")
            host = None
            if connectArgs[0]:
                if "|" in connectArgs[0]:  # if specified port
                    host = connectArgs[0].replace("|", ":")
            _connections[connectParams] = PgSQL.connect(connectParams, host=host)
        except PgSQL.Error:
            # XXX Do not raise the connect string! The trace may be seen
            # by users!!!
            raise SkunkStandardError, ("cannot connect to PostgreSQL: %s" % (sys.exc_info()[1],))

    return _connections[connectParams]
开发者ID:BackupTheBerlios,项目名称:skunkweb-svn,代码行数:27,代码来源:PyPgSQLcache.py


示例13: launchCachingProcess

	def launchCachingProcess(self):
		while self.SNMPcc.isRunning():
			self.logDebug("SNMP community caching is running, waiting 10 seconds")
			time.sleep(10)

		try:
			pgsqlCon = PgSQL.connect(host=zConfig.pgHost, user=zConfig.pgUser, password=zConfig.pgPwd, database=zConfig.pgDB)
			pgcursor = pgsqlCon.cursor()
			pgcursor.execute("SELECT ip,name,vendor FROM device ORDER BY ip")
			try:
				pgres = pgcursor.fetchall()
				for idx in pgres:
					while self.getThreadNb() >= self.max_threads:
						time.sleep(1)

					devip = idx[0]
					devname = idx[1]
					vendor = idx[2]

					devcom = self.SNMPcc.getReadCommunity(devname)
					if devcom == None:
						self.logError("No read community found for %s" % devname)
					else:
						thread.start_new_thread(self.fetchSNMPInfos,(devip,devname,devcom,vendor))
				""" Wait 1 second to lock program, else if script is too fast,it exists without discovering"""
				time.sleep(1)
			except StandardError, e:
				self.logCritical(e)
				
		except PgSQL.Error, e:
			self.logCritical("Pgsql Error %s" % e)
			return
开发者ID:nerzhul,项目名称:Z-Eye,代码行数:32,代码来源:PortIDCacher.py


示例14: rellenarTablas

def rellenarTablas(db):
    """Rellena en PostgreSQL las tablas de la base de datos indicada por "db".
    @param db: Nombre de la base de datos
    @type db: str"""
    conexion = PgSQL.connect(database=db)
    conexion.autocommit = 1
    cursor = conexion.cursor()
    sql = "INSERT INTO recetas (nombre, raciones, autor) VALUES ('Paella',4,'Greg Walters')"
    cursor.execute(sql)

    instrucciones = ['1. Sofreír la carne picada', '2. Mezclar el resto de ingredientes', '3. Dejar que rompa a hervir', '4. Dejar cocer durante 20 minutos o hasta que pierda el agua']

    for paso in instrucciones:
        sql = "INSERT INTO instrucciones (nombre_receta, paso) VALUES ('Paella','%s')" % paso
        cursor.execute(sql)

    ingredientes = ['1 taza de arroz', 'carne picada', '2 vasos de agua', '1 lata de salsa de tomate', '1 cebolla picada', '1 ajo', '1 cucharadita de comino', '1 cucharadita de orégano', 'sal y pimienta al gusto', 'salsa al gusto']

    for ingrediente in ingredientes:
        sql = "INSERT INTO ingredientes (nombre_receta, ingrediente) VALUES ('Paella','%s')" % ingrediente
        cursor.execute(sql)

    print '"Paella" insertada en el recetario'

    cursor.close()

    del cursor
    del conexion
开发者ID:lopecillo,项目名称:scripts,代码行数:28,代码来源:recetario_pgsql.py


示例15: launchCachingProcess

	def launchCachingProcess(self):
		starttime = datetime.datetime.now()
		Logger.ZEyeLogger().write("Port ID caching started")
		try:
			pgsqlCon = PgSQL.connect(host=netdiscoCfg.pgHost,user=netdiscoCfg.pgUser,password=netdiscoCfg.pgPwd,database=netdiscoCfg.pgDB)
			pgcursor = pgsqlCon.cursor()
			pgcursor.execute("SELECT ip,name,vendor FROM device ORDER BY ip")
			try:
				pgres = pgcursor.fetchall()
				for idx in pgres:
					while self.getThreadNb() >= self.max_threads:
						time.sleep(1)

					pgcursor.execute("SELECT snmpro FROM z_eye_snmp_cache where device = '%s'" % idx[1])
					pgres2 = pgcursor.fetchone()
			
					devip = idx[0]
					devname = idx[1]
					vendor = idx[2]
					if pgres2:
						devcom = pgres2[0]
					else:
						devcom = self.defaultSNMPRO
					thread.start_new_thread(self.fetchSNMPInfos,(devip,devname,devcom,vendor))
				""" Wait 1 second to lock program, else if script is too fast,it exists without discovering"""
				time.sleep(1)
			except StandardError, e:
				Logger.ZEyeLogger().write("Port ID Caching: FATAL %s" % e)
				
		except PgSQL.Error, e:
			Logger.ZEyeLogger().write("Port ID Caching: Pgsql Error %s" % e)
			sys.exit(1);	
开发者ID:jp-morvan,项目名称:Z-Eye,代码行数:32,代码来源:PortIDCacher.py


示例16: cleanRadius

def cleanRadius(dbhost,dbport,dbname):
	global threadCounter
	try:
		tc_mutex.acquire()
                threadCounter += 1
                tc_mutex.release()
		pgsqlCon = PgSQL.connect(host=netdiscoCfg.pgHost,user=netdiscoCfg.pgUser,password=netdiscoCfg.pgPwd,database=netdiscoCfg.pgDB)
        	pgcursor = pgsqlCon.cursor()
		pgcursor.execute("SELECT login,pwd FROM z_eye_radius_db_list where addr='%s' and port='%s' and dbname='%s'" % (dbhost,dbport,dbname))
        	pgres2 = pgcursor.fetchone()
		if(pgres2):
			try:
				mysqlconn = MySQLdb.connect(host=dbhost,user=pgres2[0],passwd=pgres2[1],port=dbport,db=dbname)
				zeye_log("[Z-Eye][Radius-Cleaner] Connect to MySQL DB %[email protected]%s:%s (user %s)" % (dbname,dbhost,dbport,pgres2[0]))
				mysqlcur = mysqlconn.cursor()
				mysqlcur.execute("SELECT username from z_eye_radusers WHERE expiration < NOW()")
				mysqlres = mysqlcur.fetchall()
				for idx in mysqlres:
					mysqlcur.execute("DELETE FROM radcheck WHERE username = '%s'" % idx[0])
					mysqlcur.execute("DELETE FROM radreply WHERE username = '%s'" % idx[0])
					mysqlcur.execute("DELETE FROM radusergroup WHERE username = '%s'" % idx[0])
				mysqlconn.commit()
				mysqlcur.close()
				mysqlconn.close()
			except MySQLdb.Error, e:
				zeye_log("[Z-Eye][Radius-Cleaner] MySQL Error %s" % e)
			        sys.exit(1)
		tc_mutex.acquire()
                threadCounter = threadCounter - 1
                tc_mutex.release()
                pgsqlCon.close()
开发者ID:jp-morvan,项目名称:Z-Eye,代码行数:31,代码来源:clean_radius.py


示例17: __init__

 def __init__(self, host, port, database, username, password) :
     IDB.__init__(self)
     self.dbh = PgSQL.connect(":".join([host, port, database, username, password]))
     self.albumtreestore = gtk.TreeStore(gobject.TYPE_PYOBJECT,
                                         str, gtk.gdk.Pixbuf, int, int)
     self.canViewExtensions = [
         '.jpg',
         '.jpeg',
         '.thm',
         ]
     self.canTrackExtensions = [
         '.bmp',
         '.png',
         '.jpeg',
         '.jpg',
         '.thm',
         '.gif',
         '.pcx',
         '.pnm',
         '.tiff',
         '.tiff',
         '.iff',
         '.xpm',
         '.ico',
         '.cur',
         '.ani',
         ]
开发者ID:danlyke,项目名称:imagemanager,代码行数:27,代码来源:IDB.py


示例18: DBExecute

  def DBExecute(self, query, *args):
    """Execute a query on the database, creating a connection if necessary.

    Args:
      query: SQL string
    Returns:
      Full query result in virtual table
    """
    if not self._dbh:
      if FLAGS['db-type'] == 'mysql':
        self._dbh = MySQLdb.connect(host=FLAGS['db-hostname'],
                                    user=FLAGS['db-username'],
                                    passwd=FLAGS['db-password'],
                                    db=FLAGS['db-name'])
      elif FLAGS['db-type'] == 'pgsql':
        self._dbh = PgSQL.connect(host=FLAGS['db-hostname'],
                                  user=FLAGS['db-username'],
                                  password=FLAGS['db-password'],
                                  database=FLAGS['db-name'])
      else:
        print 'Invalid db-type: %s' % FLAGS['db-type']
        sys.exit(1)
      self._cursor = self._dbh.cursor()
    self._cursor.execute(query, args)
    self._dbh.commit()
    try:
      result = self._cursor.fetchall()
    except MySQLdb.Error:
      return None
    if not result:
      return result
    fields = [i[0] for i in self._cursor.description]
    return VirtualTable(fields, result)
开发者ID:mdickers47,项目名称:statspipeline,代码行数:33,代码来源:pipelineblock.py


示例19: _setPgsqlDictCursor

    def _setPgsqlDictCursor(self):
        use=None
        try:
            from pyPgSQL import PgSQL
            use='pgsql'
        except:
            pass
            
        try:
            import psycopg2
            import psycopg2.extras
            use='psycopg2'
        except:
            pass
            
        if use=='pgsql':
            conn = PgSQL.connect(database=self.getConfig('db'),host=self.getConfig('host'),
                user=self.getConfig('user'),password=self.getConfig('pass'))
            conn.autocommit=1
            self._conn = conn
            self._cursor = conn.cursor()
        
        elif use=='psycopg2':
            conn = psycopg2.connect("host=%s dbname=%s user=%s password=%s" % (\
                    self.getConfig('host'), self.getConfig('user'), \
                    self.getConfig('db'), self.getConfig('pass')))
            conn.set_isolation_level(0)
            self._conn = conn
            self._cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        
        else:
            raise novalidDriver, "no postgres driver available (PgSQL or psycopg2)"

        assert(self._cursor)
开发者ID:alniaky,项目名称:dbmail,代码行数:34,代码来源:Dbmail.py


示例20: __init__

 def __init__(self):
     host = 'localhost'
     dbname = 'clue'
     user = 'clue'
     passwd = 'clue'
     self.cnx = PgSQL.connect('%s::%s:%s:%s' % (host, dbname, user, passwd))
     self.cur = self.cnx.cursor()
开发者ID:emnh,项目名称:clue-dictionary-client,代码行数:7,代码来源:wordcluster.py



注:本文中的pyPgSQL.PgSQL类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mesh.mesh函数代码示例发布时间:2022-05-25
下一篇:
Python pyPdf.PdfFileWriter类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap