Python:操作PostgreSQL数据库(使用DB API2.0)

 

分类: 数据库 Python 脚本语言 PostgreSQL 546人阅读 评论(0) 收藏 举报

   昨天在《Python:操作PostgreSQL数据库(使用PyGreSQL)》一文中使用PyGreSQL模块实现了对PostgreSQL数据库的操作,今天使用另一种python通用的数据库访问接口DB API2.0来实现一下同样的操作,其实在《Python:操作嵌入式数据库SQLite》一文中我们使用的就是DB API2.0,我们可以看到,它对不同数据库提供了统一的访问接口,更多关于DB API2.0的介绍请参考http://www.python.org/dev/peps/pep-0249/

   来看看实现,首先我们要下载提供DB API2.0接口的模块psycopg2,路径:http://initd.org/psycopg/download/,此模块API手册地址为:http://initd.org/psycopg/docs/index.html

一、实现:

 

  1. #!/usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3.   
  4. #导入日志及psycopg2模块  
  5. import logging  
  6. import logging.config  
  7. import psycopg2  
  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-13 
  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-13 
  35.     '''    
  36.     pgdb_logger.debug("operate_postgre_tbl_product enter...")   
  37.       
  38.     #连接数据库    
  39.     try:  
  40.         pgdb_conn = psycopg2.connect(database = 'kevin_test', user = 'dyx1024', password = '888888', host = '192.168.230.128')  
  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.     pg_cursor = pgdb_conn.cursor()  
  49.           
  50.     #删除表  
  51.     sql_desc = "DROP TABLE IF EXISTS tbl_product3;"  
  52.     try:  
  53.         pg_cursor.execute(sql_desc)  
  54.     except Exception, e:  
  55.         print 'drop table failed'  
  56.         pgdb_logger.error("drop table failed, ret = %s" % e.args[0])  
  57.         pg_cursor.close()  
  58.         pgdb_conn.close()    
  59.         return  
  60.     pgdb_conn.commit()  
  61.       
  62.     pgdb_logger.info("drop table(tbl_product3) succ.")   
  63.     
  64.     #创建表  
  65.     sql_desc = '''''CREATE TABLE tbl_product3( 
  66.         i_index INTEGER, 
  67.         sv_productname VARCHAR(32) 
  68.         );'''  
  69.     try:      
  70.         pg_cursor.execute(sql_desc)  
  71.     except Exception, e:  
  72.         print 'create table failed'  
  73.         pgdb_logger.error("create table failed, ret = %s" % e.args[0])  
  74.         pg_cursor.close()  
  75.         pgdb_conn.close()    
  76.         return  
  77.     pgdb_conn.commit()        
  78.      
  79.     pgdb_logger.info("create table(tbl_product3) succ.")   
  80.         
  81.     #插入记录     
  82.     sql_desc = "INSERT INTO tbl_product3(sv_productname) values('apple')"  
  83.     try:  
  84.         pg_cursor.execute(sql_desc)  
  85.     except Exception, e:  
  86.         print 'insert record into table failed'  
  87.         pgdb_logger.error("insert record into table failed, ret = %s" % e.args[0])  
  88.         pg_cursor.close()  
  89.         pgdb_conn.close()    
  90.         return      
  91.     pgdb_conn.commit()  
  92.        
  93.     pgdb_logger.info("insert record into table(tbl_product3) succ.")       
  94.   
  95.     #查询表方法一          
  96.     sql_desc = "select * from tbl_product3"  
  97.     try:  
  98.         pg_cursor.execute(sql_desc)  
  99.     except Exception, e:  
  100.         print 'select record from  table tbl_product3 failed'  
  101.         pgdb_logger.error("select record from  table tbl_product3 failed, ret = %s" % e.args[0])  
  102.         pg_cursor.close()  
  103.         pgdb_conn.close()    
  104.         return        
  105.         
  106.     for row in pg_cursor:  
  107.         print row   
  108.         pgdb_logger.info("%s", row)     
  109.       
  110.     print '*' * 20      
  111.     #查询表方法二       
  112.     sql_desc = "select * from tbl_test_port"  
  113.     try:  
  114.         pg_cursor.execute(sql_desc)  
  115.     except Exception, e:  
  116.         print 'select record from  table tbl_test_port failed'  
  117.         pgdb_logger.error("select record from  table tbl_test_port failed, ret = %s" % e.args[0])  
  118.         pg_cursor.close()  
  119.         pgdb_conn.close()    
  120.         return    
  121.               
  122.     for row in pg_cursor.fetchall():  
  123.         print row   
  124.         pgdb_logger.info("%s", row)                
  125.        
  126.     #关闭数据库连接       
  127.     pg_cursor.close()  
  128.     pgdb_conn.close()         
  129.       
  130.     pgdb_logger.debug("operate_sqlite3_tbl_product leaving...")   
  131.   
  132. if __name__ == '__main__':   
  133.       
  134.     #初始化日志系统  
  135.     pgdb_logger = log_init(LOG_FILENAME, LOG_CONTENT_NAME)     
  136.       
  137.     #操作数据库  
  138.     operate_postgre_tbl_product()  
  139.       

二、测试:

 

1、命令行结果:

 

  1. (None, 'apple')  
  2. ********************  
  3. (1, 2, 1)  
  4. (2, 3, 1)  
  5. (3, 5, 1)  
  6. (5, 0, 1)  
  7. (7, 18, 1)  
  8. (8, 8, 1)  
  9. (9, 7, 1)  
  10. (10, 21, 1)  
  11. (11, 23, 1)  
  12. (12, 29, 1)  
  13. (4, 3000, 1)  

2、日志文件结果:

 

 

  1. [2012-02-14 00:12:06,358  pg_log]DEBUG:  operate_postgre_tbl_product enter... (db_postgre.py:36)  
  2. [2012-02-14 00:12:06,453  pg_log]INFO:  conntect postgre database(kevin_test) succ. (db_postgre.py:46)  
  3. [2012-02-14 00:12:06,467  pg_log]INFO:  drop table(tbl_product3) succ. (db_postgre.py:62)  
  4. [2012-02-14 00:12:06,483  pg_log]INFO:  create table(tbl_product3) succ. (db_postgre.py:79)  
  5. [2012-02-14 00:12:06,483  pg_log]INFO:  insert record into table(tbl_product3) succ. (db_postgre.py:93)  
  6. [2012-02-14 00:12:06,483  pg_log]INFO:  (None, 'apple') (db_postgre.py:108)  
  7. [2012-02-14 00:12:06,483  pg_log]INFO:  (1, 2, 1) (db_postgre.py:124)  
  8. [2012-02-14 00:12:06,483  pg_log]INFO:  (2, 3, 1) (db_postgre.py:124)  
  9. [2012-02-14 00:12:06,483  pg_log]INFO:  (3, 5, 1) (db_postgre.py:124)  
  10. [2012-02-14 00:12:06,483  pg_log]INFO:  (5, 0, 1) (db_postgre.py:124)  
  11. [2012-02-14 00:12:06,483  pg_log]INFO:  (7, 18, 1) (db_postgre.py:124)  
  12. [2012-02-14 00:12:06,500  pg_log]INFO:  (8, 8, 1) (db_postgre.py:124)  
  13. [2012-02-14 00:12:06,500  pg_log]INFO:  (9, 7, 1) (db_postgre.py:124)  
  14. [2012-02-14 00:12:06,500  pg_log]INFO:  (10, 21, 1) (db_postgre.py:124)  
  15. [2012-02-14 00:12:06,500  pg_log]INFO:  (11, 23, 1) (db_postgre.py:124)  
  16. [2012-02-14 00:12:06,500  pg_log]INFO:  (12, 29, 1) (db_postgre.py:124)  
  17. [2012-02-14 00:12:06,500  pg_log]INFO:  (4, 3000, 1) (db_postgre.py:124)  
  18. [2012-02-14 00:12:06,500  pg_log]INFO:  (6, 1999, 1) (db_postgre.py:124)  
  19. [2012-02-14 00:12:06,500  pg_log]DEBUG:  operate_sqlite3_tbl_product leaving... (db_postgre.py:130)  

 

posted @ 2012-05-05 11:19  codewei  阅读(237)  评论(0)    收藏  举报