接上篇 三、連接oracle之配置文件 為了增加程式的可移植性,將 db = cx_Oracle.connect('bss_cpc/[email protected]/orcl') 修改為: db = cx_Oracle(connStr),connStr值從配置文件中讀取。 讀取配置文件可 ...
接上篇
三、連接oracle之配置文件
為了增加程式的可移植性,將
db = cx_Oracle.connect('bss_cpc/[email protected]/orcl')
修改為:
db = cx_Oracle(connStr),connStr值從配置文件中讀取。
讀取配置文件可以使用內置模塊
import configparser -->python3 import ConfigParser -->python2
本人的配置文件內容:
[oracle]
db_user = bss_cpc
db_pass = bss_cpc
db_host = 192.168.128.49
db_port =
db_space =
db_inst = orcl
cf = configparser.ConfigParser()
#讀取文件 (如果文件和python不在一個目錄下,需要包含路徑)
cf.read("文件")
#將文件下section為oracle的內容讀取並賦值給變數
user = cf.get("oracle","db_user")
_pass = cf.get("oracle","db_pass")
host = cf.get("oracle","db_host")
port = cf.get("oracle","db_port")
inst = cf.get("oracle","db_inst")
有的連接可以不加埠,為了區別加了判斷
if port == "":
connStr = user + '/' +_pass + '@' + host + '/' +inst
else:
connStr = user + '/' +_pass + '@' + host + ':' + 'port' + '/' +inst
db = cx_Oracle(connStr)
到此讀取配置文件連oracle搞定,剩下的都是簡單的執行了。如有疑問或是更好的意見可以留言,我們可以一起學習,共同進步,另外今年python已超越java成為全球最受歡迎的編程語言了,加油!!!
附configparser基本操作
1.基本的讀取配置文件
-read(filename) 直接讀取ini文件內容
-sections() 得到所有的section,並以列表的形式返回
-options(section) 得到該section的所有option
-items(section) 得到該section的所有鍵值對
-get(section,option) 得到section中option的值,返回為string類型
-getint(section,option) 得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數。
2.基本的寫入配置文件
-add_section(section) 添加一個新的section
-set( section, option, value) 對section中的option進行設置,需要調用write將內容寫入配置文件