设为首页 收藏本站
查看: 883|回复: 0

[经验分享] Python:操作PostgreSQL数据库(使用PyGreSQL)

[复制链接]

尚未签到

发表于 2016-11-20 09:09:35 | 显示全部楼层 |阅读模式
  昨天使用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》
  《PostgreSQL服务端监听设置及客户端连接方法》
  《PostgreSQL数据库创建、删除方法》
  更多PostgreSQL相关知识请访问从我的博客专栏:PostgreSQL系列
  三、程序实现:
  #!/usr/bin/env python# -*- coding: utf-8 -*-#导入日志及pg模块import loggingimport logging.configimport pg#日志配置文件名LOG_FILENAME = 'logging.conf'#日志语句提示信息LOG_CONTENT_NAME = 'pg_log'def log_init(log_config_filename, logname):'''Function:日志模块初始化函数Input:log_config_filename:日志配置文件名lognmae:每条日志前的提示语句Output: loggerauthor: socratesdate:2012-02-12'''logging.config.fileConfig(log_config_filename)logger = logging.getLogger(logname)return loggerdef operate_postgre_tbl_product():'''Function:操作pg数据库函数Input:NONEOutput: NONEauthor: socratesdate: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()  returnpgdb_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 rowpgdb_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()
四、测试:
  1、运行后命令行打印结果:
  {'sv_productname': 'apple', 'i_index': None}{'i_status': 1, 'i_port': 2, 'i_index': 1}{'i_status': 1, 'i_port': 3, 'i_index': 2}{'i_status': 1, 'i_port': 5, 'i_index': 3}{'i_status': 1, 'i_port': 0, 'i_index': 5}{'i_status': 1, 'i_port': 18, 'i_index': 7}{'i_status': 1, 'i_port': 8, 'i_index': 8}{'i_status': 1, 'i_port': 7, 'i_index': 9}{'i_status': 1, 'i_port': 21, 'i_index': 10}{'i_status': 1, 'i_port': 23, 'i_index': 11}{'i_status': 1, 'i_port': 29, 'i_index': 12}{'i_status': 1, 'i_port': 3000, 'i_index': 4}{'i_status': 1, 'i_port': 1999, 'i_index': 6}2、日志文件内容:
  [2012-02-12 18:09:53,536  pg_log]DEBUG:  operate_postgre_tbl_product enter... (test_func.py:36)[2012-02-12 18:09:53,772  pg_log]INFO:  conntect postgre database(kevin_test) succ. (test_func.py:46)[2012-02-12 18:09:53,786  pg_log]INFO:  drop table(tbl_product3) succ. (test_func.py:58)[2012-02-12 18:09:53,802  pg_log]INFO:  create table(tbl_product3) succ. (test_func.py:73)[2012-02-12 18:09:53,802  pg_log]INFO:  insert record into table(tbl_product3) succ. (test_func.py:85)[2012-02-12 18:09:53,802  pg_log]INFO:  {'sv_productname': 'apple', 'i_index': None} (test_func.py:91)[2012-02-12 18:09:53,802  pg_log]INFO:  {'i_status': 1, 'i_port': 2, 'i_index': 1} (test_func.py:97)[2012-02-12 18:09:53,802  pg_log]INFO:  {'i_status': 1, 'i_port': 3, 'i_index': 2} (test_func.py:97)[2012-02-12 18:09:53,802  pg_log]INFO:  {'i_status': 1, 'i_port': 5, 'i_index': 3} (test_func.py:97)[2012-02-12 18:09:53,802  pg_log]INFO:  {'i_status': 1, 'i_port': 0, 'i_index': 5} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]INFO:  {'i_status': 1, 'i_port': 18, 'i_index': 7} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]INFO:  {'i_status': 1, 'i_port': 8, 'i_index': 8} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]INFO:  {'i_status': 1, 'i_port': 7, 'i_index': 9} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]INFO:  {'i_status': 1, 'i_port': 21, 'i_index': 10} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]INFO:  {'i_status': 1, 'i_port': 23, 'i_index': 11} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]INFO:  {'i_status': 1, 'i_port': 29, 'i_index': 12} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]INFO:  {'i_status': 1, 'i_port': 3000, 'i_index': 4} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]INFO:  {'i_status': 1, 'i_port': 1999, 'i_index': 6} (test_func.py:97)[2012-02-12 18:09:53,819  pg_log]DEBUG:  operate_sqlite3_tbl_product leaving... (test_func.py:101)
3、psql查看结果:
  [iyunv@kevin ~]# su - postgres[postgres@kevin ~]$ psql -U dyx1024 -d kevin_testpsql (8.4.2)Type "help" for help.kevin_test=# \dtList of relationsSchema |     Name      | Type  |     Owner      --------+---------------+-------+----------------public | tbl_product3  | table | dyx1024public | tbl_test_port | table | pg_test_user_3(2 rows)kevin_test=# select * from tbl_product3;i_index | sv_productname ---------+----------------| apple(1 row)kevin_test=# select * from tbl_test_port;i_index | i_port | i_status ---------+--------+----------1 |      2 |        12 |      3 |        13 |      5 |        15 |      0 |        17 |     18 |        18 |      8 |        19 |      7 |        110 |     21 |        111 |     23 |        112 |     29 |        14 |   3000 |        16 |   1999 |        1(12 rows)kevin_test=# \q[postgres@kevin ~]$


  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-302727-1-1.html 上篇帖子: org.postgresql.jdbc4.Jdbc4PreparedStatement.setQueryTimeout(int)...错误 下篇帖子: postgresql 数据文件损坏回复实验
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表