# -*- coding: utf-8 -*-
import cx_Oracle
import sys
import urllib
import os
#连接数据库
def connectDB(dbname='orcl'):
if dbname == 'orcl':
tns=cx_Oracle.makedsn('192.168.1.1',1521,'test')
db=cx_Oracle.connect('admin','admin',tns)
return db
#查询数据库
def sqlSelect(sql,db):
#include:select
cr=db.cursor()
cr.execute(sql)
rs=cr.fetchall()
cr.close()
return rs
#插入数据库
def sqlDML(sql,db):
#include: insert,update,delete
cr=db.cursor()
cr.execute(sql)
cr.close()
db.commit()
#使用参数查询数据库
def sqlDML2(sql,params,db):
# execute dml with parameters
cr=db.cursor()
cr.execute(sql,params)
cr.close()
db.commit()
#删除数据库
def sqlDDL(sql,db):
#include: create
cr=db.cursor()
cr.execute(sql)
cr.close()
#删除表
def sqlDT(sql,db):
#drop table
cr=db.cursor()
cr.execute(sql)
cr.close()
#测试数据库
if __name__=='__main__':
print "This is a test python program!\n"
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.UTF8'
# os.environ['NLS_LANG']='AMERICAN_AMERICA.ZHS16GBK'
#connect to database:
db=connectDB()
#create a table:
sql='CREATE table IF NOT EXISTS PER_INFO(id number,name varchar2(20),phone number)'
sqlDDL(sql,db)
#insert data to table dave:
sql='insert into PER_INFO values(1,\'yjq\',18505791228)'
sqlDML(sql,db)
dt=[{'id':2,'name':'john','phone':18505791125},
# {'id':3,'name':'atom','phone':18505791226},
{'id':4,'name':'king','phone':18505791227}]
sql='insert into PER_INFO values(:id,:name,:phone)'
for x in dt:
sqlDML2(sql,x,db)
#select the result:
print "this is the first time select the data from PER_INFO"
sql='SELECT * FROM PER_INFO'
rs=sqlSelect(sql,db)
for x in rs:
print x
#update data where id=1,change the name to anhui
sql='UPDATE PER_INFO set name=\'yjq\' where id=1'
sqlDML(sql,db)
#select again:
print "\n change the nanme to anhui where id equal 1,and select the result"
sql='SELECT * FROM PER_INFO'
rs=sqlSelect(sql,db)
for x in rs:
print x
#delete data where id=3
sql='DELETE FROM PER_INFO where id=1'
sqlDML(sql,db)
#select again:
print "\n select the result"
sql='SELECT * FROM PER_INFO '
rs=sqlSelect(sql,db)
for x in rs:
print x
print "delete table"
sql='DROP table PER_INFO '
sqlDT(sql,db)
print "process over"
db.close()