cx_Oracle增删改查

2017-01-09 14:06:16来源:作者:st4024589553人点击


import cx_Oracle

连接
dsn=cx_Oracle.makedsn(host, int(port), dbname)
self.conn = cx_Oracle.connect(user, passwd ,dsn)
self.cursor = self.conn.cursor()

def insert(self, sql, param, flag = True):
sql = self.sqltran(sql, param)
self.cursor.execute(sql)
self.conn.commit()

def selectall(self, sql, param=None):
sql = self.sqltran(sql, param)
self.cursor.execute(sql)
result = self.cursor.fetchall()
return result
更新
def update(self, sql, param=None, flag = True):
sql = self.sqltran(sql, param)
self.cursor.execute(sql)
self.conn.commit()

def delete(self, sql, param=None):
sql = self.sqltran(sql, param)
self.cursor.execute(sql)
self.conn.commit()
关闭连接
def __del__( self ):
if self.conn :
self.conn.close()
sql转换
def sqltran(self,sql,param):
for i in range(0,len(param)):
sql = sql.replace('%s',str(param[i]),1)
return sql
测试方法
if __name__ == '__main__':
param = ('id','name','addr',1)
sql1= 'select id ,name, addr from test'
sql0= 'select %s,%s,%s from test'
sql2= 'insert into test (%s,%s,%s)values(4,4,4)'
sql3= 'update test set name=222 where id=%s'
sql4= 'delete from test where id=%s'
print oracle.selectall(sql0,param)
print oracle.insert(sql2, param)
print oracle.selectOne(sql0,param)
print oracle.update(sql3,('3'))
print oracle.delete(sql4,('4'))
print oracle.selectall(sql0,param)
print 'success'

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台