這裡(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 Files\PostgreSQL\8.3\lib
E:\Program Files\PostgreSQL\8.3\bin
2、將python安裝目錄C:\Python26\Lib\site-packages\pywin32_system32下的dll文件拷貝到C:\WINDOWS\system32
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?
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
-
- #導入日志及pg模塊
- import logging
- import logging.config
- import pg
-
- #日志配置文件名
- LOG_FILENAME = 'logging.conf'
-
- #日志語句提示信息
- LOG_CONTENT_NAME = 'pg_log'
-
- def log_init(log_config_filename, logname):
- '''''
- Function:日志模塊初始化函數
- Input:log_config_filename:日志配置文件名
- lognmae:每條日志前的提示語句
- Output: logger
- author: socrates
- date:2012-02-12
- '''
- logging.config.fileConfig(log_config_filename)
- logger = logging.getLogger(logname)
- return logger
-
- def operate_postgre_tbl_product():
- '''''
- Function:操作pg數據庫函數
- Input:NONE
- Output: NONE
- author: socrates
- date:2012-02-12
- '''
- pgdb_logger.debug("operate_postgre_tbl_product enter...")
-
- #連接數據庫
- try:
- pgdb_conn = pg.connect(dbname = 'kevin_test', host = '192.168.230.128', user = 'dyx1024', passwd = '888888')
- except Exception, e:
- print e.args[0]
- pgdb_logger.error("conntect postgre database failed, ret = %s" % e.args[0])
- return
-
- pgdb_logger.info("conntect postgre database(kevin_test) succ.")
-
- #刪除表
- sql_desc = "DROP TABLE IF EXISTS tbl_product3;"
- try:
- pgdb_conn.query(sql_desc)
- except Exception, e:
- print 'drop table failed'
- pgdb_logger.error("drop table failed, ret = %s" % e.args[0])
- pgdb_conn.close()
- return
-
- pgdb_logger.info("drop table(tbl_product3) succ.")
-
- #創建表
- sql_desc = '''''CREATE TABLE tbl_product3(
- i_index INTEGER,
- sv_productname VARCHAR(32)
- );'''
- try:
- pgdb_conn.query(sql_desc)
- except Exception, e:
- print 'create table failed'
- pgdb_logger.error("create table failed, ret = %s" % e.args[0])
- pgdb_conn.close()
- return
-
- pgdb_logger.info("create table(tbl_product3) succ.")
-
- #插入記錄
- sql_desc = "INSERT INTO tbl_product3(sv_productname) values('apple')"
- try:
- pgdb_conn.query(sql_desc)
- except Exception, e:
- print 'insert record into table failed'
- pgdb_logger.error("insert record into table failed, ret = %s" % e.args[0])
- pgdb_conn.close()
- return
-
- pgdb_logger.info("insert record into table(tbl_product3) succ.")
-
- #查詢表 1
- sql_desc = "select * from tbl_product3"
- for row in pgdb_conn.query(sql_desc).dictresult():
- print row
- pgdb_logger.info("%s", row)
-
- #查詢表2
- sql_desc = "select * from tbl_test_port"
- for row in pgdb_conn.query(sql_desc).dictresult():
- print row
- pgdb_logger.info("%s", row)
-
- #關閉數據庫連接
- pgdb_conn.close()
- pgdb_logger.debug("operate_sqlite3_tbl_product leaving...")
-
- if __name__ == '__main__':
-
- #初始化日志系統
- pgdb_logger = log_init(LOG_FILENAME, LOG_CONTENT_NAME)
-
- #操作數據庫
- operate_postgre_tbl_product()
-