zoukankan      html  css  js  c++  java
  • 使用ConfigParser和psycopg2 访问PostgreSQL

    Psycopg Python 语言的 PostgreSQL 数据库接口。 它的主要优势在于完全支持Python DB API 2.0,以及安全的多线程支持。它适用于随时创建、销毁大量游标的、和产生大量并发INSERTUPDATE操作的多线程数据库应用。Psycopg包内含 ZPsycopgDA,一个Zope数据库接口。--摘自好搜百科

    在使用这个之前,需要从官网下载该安装包,使用过psycopg2-2.5.4.win32-py2.7-pg9.3.5-release.exe(针对windows x86)。

    ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。如下格式:

    [srv]
    ip = 127.0.0.1

    port = 5360

    实例说明:

    # 引入psycopg2和ConfigParser库

    import psycopg2

    import ConfigParser

    #使用ConfigParser 首选需要初始化实例,并读取配置文件:

    INITXT="test.ini"
    config = ConfigParser.ConfigParser()
    config.readfp(open(INITXT))
    ip = config.get("srv","ip")
    port = config.get("srv","port")

    # 连接到数据库test

    conn = psycopg2.connect('host=%s port=%s dbname=test user=ent password=enttest'%(ip,port))

    # 建立Cursor对象

    cur = conn.cursor()

    #执行sql语句,并获取结果

    sql = cur.execute('''select mid from t_user limit 1''')

    mid = cur.fetchone()
    print mid[0]

    # 提交数据改变
    conn.commit()
     
    # 关闭Cursor对象和连接对象
    cur.close()
    conn.close()
  • 相关阅读:
    Recommender Systems 基于知识的推荐
    粒子群优化算法简介
    彻底弄懂LSH之simHash算法
    c++ 字符串函数用法举例
    Linux上的运行的jar包
    推荐系统判定标准
    python 细枝末节
    PV UV
    python解析json
    生成n对括号的所有合法排列
  • 原文地址:https://www.cnblogs.com/skyer/p/4301722.html
Copyright © 2011-2022 走看看