Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python:操作PostgreSQL数据库(使用PyGreSQL)

这里(http://www.linuxidc.com/Linux/2012-02/54213.htm)写了使用python写了操作嵌入式数据库SQLite的方法,今天用python写了针对个人比较熟悉的开源数据库PostgreSQL的常用操作,开发过程简介如下:一、环境信息:    1、操作系统:        RedHat Enterprise Linux 4        Windows XP SP2  2、数据库:        PostgreSQL8.3  3、 开发工具:        Eclipse+Pydev+python2.6+PyGreSQL(提供pg模块)  4、说明:        a、PostgreSQL数据库运行于RedHat Linux上,Windows下也要安装pgAdmin(访问PostgreSQL服务器的客户端)。        b、PyGreSQL(即pg)模块下载路径及API手册:http://www.pygresql.org/二、配置:       1、将pgAdmin安装路径下以下子目录添加到系统环境变量中:             E:Program FilesPostgreSQL8.3lib             E:Program FilesPostgreSQL8.3in       2、将python安装目录C:Python26Libsite-packagespywin32_system32下的dll文件拷贝到C:WINDOWSsystem32       3、说明:a. 如果跳过以上两步,在import pg时将会报错,浪费较长时间才搞定。b. 如果对PostgreSQL安装和配置不熟悉,请参考本博客中以下几篇文章:《RedHat Linux上安装PostgreSQL》 http://www.linuxidc.com/Linux/2011-08/40521.htm《PostgreSQL服务端监听设置及客户端连接方法》 http://www.linuxidc.com/Linux/2011-08/40528.htm《PostgreSQL数据库创建、删除方法》 http://www.linuxidc.com/Linux/2011-08/40525.htm三、程序实现:[python] view plaincopyprint?
  1. #!/usr/bin/env python   
  2. # -*- coding: utf-8 -*-   
  3.   
  4. #导入日志及pg模块   
  5. import logging  
  6. import logging.config  
  7. import pg  
  8.   
  9. #日志配置文件名   
  10. LOG_FILENAME = "logging.conf"  
  11.   
  12. #日志语句提示信息   
  13. LOG_CONTENT_NAME = "pg_log"  
  14.   
  15. def log_init(log_config_filename, logname):  
  16.     """"" 
  17.     Function:日志模块初始化函数 
  18.     Input:log_config_filename:日志配置文件名 
  19.            lognmae:每条日志前的提示语句 
  20.     Output: logger 
  21.     author: socrates 
  22.     date:2012-02-12 
  23.     """  
  24.     logging.config.fileConfig(log_config_filename)  
  25.     logger = logging.getLogger(logname)  
  26.     return logger  
  27.   
  28. def operate_postgre_tbl_product():  
  29.     """"" 
  30.     Function:操作pg数据库函数 
  31.     Input:NONE 
  32.     Output: NONE 
  33.     author: socrates 
  34.     date:2012-02-12 
  35.     """    
  36.     pgdb_logger.debug("operate_postgre_tbl_product enter...")   
  37.       
  38.     #连接数据库     
  39.     try:  
  40.         pgdb_conn = pg.connect(dbname = "kevin_test", host = "192.168.230.128", user = "dyx1024", passwd = "888888")  
  41.     except Exception, e:  
  42.          print e.args[0]  
  43.          pgdb_logger.error("conntect postgre database failed, ret = %s" % e.args[0])      
  44.          return      
  45.        
  46.     pgdb_logger.info("conntect postgre database(kevin_test) succ.")   
  47.           
  48.     #删除表   
  49.     sql_desc = "DROP TABLE IF EXISTS tbl_product3;"  
  50.     try:  
  51.         pgdb_conn.query(sql_desc)  
  52.     except Exception, e:  
  53.         print "drop table failed"  
  54.         pgdb_logger.error("drop table failed, ret = %s" % e.args[0])  
  55.         pgdb_conn.close()    
  56.         return  
  57.       
  58.     pgdb_logger.info("drop table(tbl_product3) succ.")   
  59.     
  60.     #创建表   
  61.     sql_desc = """""CREATE TABLE tbl_product3( 
  62.         i_index INTEGER, 
  63.         sv_productname VARCHAR(32) 
  64.         );"""  
  65.     try:      
  66.         pgdb_conn.query(sql_desc)  
  67.     except Exception, e:  
  68.         print "create table failed"  
  69.         pgdb_logger.error("create table failed, ret = %s" % e.args[0])  
  70.         pgdb_conn.close()    
  71.         return          
  72.      
  73.     pgdb_logger.info("create table(tbl_product3) succ.")   
  74.         
  75.     #插入记录      
  76.     sql_desc = "INSERT INTO tbl_product3(sv_productname) values("apple")"  
  77.     try:  
  78.         pgdb_conn.query(sql_desc)  
  79.     except Exception, e:  
  80.         print "insert record into table failed"  
  81.         pgdb_logger.error("insert record into table failed, ret = %s" % e.args[0])  
  82.         pgdb_conn.close()    
  83.         return      
  84.        
  85.     pgdb_logger.info("insert record into table(tbl_product3) succ.")       
  86.        
  87.     #查询表 1          
  88.     sql_desc = "select * from tbl_product3"  
  89.     for row in pgdb_conn.query(sql_desc).dictresult():  
  90.         print row  
  91.         pgdb_logger.info("%s", row)   
  92.    
  93.     #查询表2           
  94.     sql_desc = "select * from tbl_test_port"  
  95.     for row in pgdb_conn.query(sql_desc).dictresult():  
  96.         print row   
  97.         pgdb_logger.info("%s", row)          
  98.        
  99.     #关闭数据库连接        
  100.     pgdb_conn.close()         
  101.     pgdb_logger.debug("operate_sqlite3_tbl_product leaving...")   
  102.   
  103. if __name__ == "__main__":   
  104.       
  105.     #初始化日志系统   
  106.     pgdb_logger = log_init(LOG_FILENAME, LOG_CONTENT_NAME)     
  107.       
  108.     #操作数据库   
  109.     operate_postgre_tbl_product()  
  110.