天天看點

python資料庫self函數_Python連接配接資料庫

Python連接配接Oracle資料庫

下載下傳cx_Oracle

在Python連接配接操作Oracle資料前,我們先要導入相應的子產品包,Python有一個子產品cx_Oracle可以與Oracle相連。

要使用cx_Oracle,就要先下載下傳安裝。我這裡預設的是用windows系統,下載下傳即點選這裡,解壓後直接打開.exe檔案運作安裝

驗證安裝是否正确:

運作 : import cx_Oracle

python資料庫self函數_Python連接配接資料庫

如果沒有報錯,則代表安裝成功。

連接配接oracle資料庫

在我們安裝好cx_Oracle子產品以後,并且導入對應的子產品,然後來連接配接我們的資料,

驗證是否連接配接成功,代碼如下:

importcx_Oracleprint 'Ready:'conn= cx_Oracle.connect('scott/[email protected]/orcl')print conn.version

對應結果:

python資料庫self函數_Python連接配接資料庫

這樣,代表我們的python程式已經連接配接上了我們本機的資料了

執行SQL語句

下面我們來執行一些sql語句,看看能否在oracle中起作用:

我們·先建立空表:

create tableperson (

name nvarchar2(20),

agenumber,

address nvarchar2(30));select * from person;

然後執行我們的插入操作:

importcx_Oracle

conn= cx_Oracle.connect('scott/[email protected]/orcl')printconn.version

c=conn.cursor()

x=c.execute('insert into person(name,age,address) values(:1,:2,:3)',['Jim',23,'大連'])

conn.commit();

c.close()

conn.close()print '大家好,大連'

如果出現中文亂碼的現象,我們可以在python中加入這麼一句話:

importos

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'

這樣執行的話,我們的資料庫中就新增了一條資料

python資料庫self函數_Python連接配接資料庫

下面我們已經在person表中插入多條資料,執行查詢語句:

conn = cx_Oracle.connect('scott/[email protected]/orcl')printconn.version

c=conn.cursor()

sql= 'select * from person'c.execute(sql)#執行sql語句

for x inc:print x[0],x[1],x[2]

結果:

python資料庫self函數_Python連接配接資料庫

調用存儲過程和函數

建立存儲過程:

create or replace procedure p_updateAgeByName(iname innvarchar2,myname out nvarchar2)isbegin

myname :=iname||',Good Morning';

end;

利用python執行存儲過程:

conn = cx_Oracle.connect('scott/[email protected]/orcl')printconn.version

c=conn.cursor()

name= 'Joe'myname=c.var(cx_Oracle.STRING)

x= c.callproc('p_updateAgeByName',[name,myname])printmynameprintmyname.getvalue()

c.close()

conn.close()

運作結果:

python資料庫self函數_Python連接配接資料庫

調用函數

importcx_Oracle

conn=cx_Oracle.connect('load/[email protected]/ora11g')

c=conn.cursor()

str1='nice'str2=c.callfunc('f_demo',cx_Oracle.STRING,[str1])print(str2)

c.close()

conn.close()

Python連接配接sqlserver資料庫

importpymssqlclassMSSQL:def __init__(self,host,user,pwd,db):

self.host=host

self.user=user

self.pwd=pwd

self.db=dbdef __GetConnect(self):if notself.db:raise(NameError,"沒有設定資料庫資訊")

self.conn= pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")

cur=self.conn.cursor()if notcur:raise(NameError,"連接配接資料庫失敗")else:returncurdefExecQuery(self,sql):

cur= self.__GetConnect()

cur.execute(sql)

resList=cur.fetchall()#查詢完畢後必須關閉連接配接

self.conn.close()returnresListdefExecNonQuery(self,sql):

cur= self.__GetConnect()

cur.execute(sql)

self.conn.commit()

self.conn.close()

怎麼執行呢?

ms = MSSQL(host="localhost",user="sa",pwd="1234",db="testdb")

sql = " "#這裡是sql語句

ms.ExecNonQuery(sql)

#-*- coding: gbk -*-

importcx_Oracleimportmath#連接配接Oracle資料庫

conn= cx_Oracle.connect('scott/[email protected]/orcl') #或者localhost

print 'Oracle資料連接配接OK'

print '資料庫的版本号是:',conn.version

c=conn.cursor()

sql= 'select * from emp'c.execute(sql)for x inc:print x[0],x[1],x[2]#判斷語句

age= 33

if age >= 18:print 'adult'

elif age >=6:print 'teenager'

else:print 'children'

#for循環語句

names= ['Michael','Bob','Tracy']for name innames:printnamefor x in range(100): #0至99這一百個數

printx#while循環

sum=0

n= 99

while n>0 :

sum= sum +n

n= n - 2

printsum#raw_input等待輸入

birth= int(raw_input('please input your birth:'))if birth > 2000:print '00後'

else:print '00前'

#dict字典的使用

d= {'Jim':95,'Bob':94,'Lucy':88}print d['Jim']#set 沒有value,沒有重複的key

s=set([1,2,3,4,2,3,1,4])prints#定義函數

defmy_abs(x):if notisinstance(x,(int,float)):raise TypeError('bad operand type')if x >0:returnxelse:return -xprint my_abs(-123)#函數傳回多個值

def move(x,y,step,angle=0):

nx=x+step*math.cos(angle)

ny=y-step*math.sin(angle)returnnx, ny

x,y=move(100,100,60,math.pi/6)printx,y

r= move(100,100,60)printrprinttype(r)#可變參數函數 必選參數 預設參數 可變參數 關鍵字參數

defcalc(numbers):

sum=0for n innumbers:

sum= sum + n*nreturnsumprint calc([1,3,5,7]) #需要傳list或者tube

def calc2(*numbers):

sum=0;for n innumbers:

sum= sum + n*nreturnsumprint calc2(1,3,5,7) #可以傳可變參數

#如果已經存在list,也可以作為參數

num=[1,2,3]print calc2(*num)#遞歸函數

deffact(n):if n==1:return 1

return n*fact(n-1)print fact(1)print fact(5)