天天看点

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)