获取数据
import cx_Oracle as cx
conn_str = 'c##my/t123@localhost:1521/orcl'#创建连接的用户,用户名/密码@服务器IP:端口/数据库名称
connection_oracle = cx.Connection(conn_str)连接数据库返回连接对象
cursor = connection_oracle.cursor()#返回游标对象
cursor.execute('select * from table1')#执行SQL语句,获取表的数据存到游标中
result= cursor.fetchall()#获取结果
print(result)
cursor.close()
connection_oracle.close()
插入数据
import cx_Oracle as cx
import random
conn_str = 'c##my/t123@localhost:1521/orcl'
connection_oracle = cx.Connection(conn_str)
cursor = connection_oracle.cursor()
age = random.randint(18,45)
#可执行,但不正确的写法
#cursor.execute("insert into table1(姓名,年龄) values('王二麻子',+str(age)+)")
#切勿将用户数据连接或插入到SQL语句中
#绑定变量是冒号前缀的标识符或数字
sql = """insert into table1(姓名,年龄)
values (:name,:nage)"""
cursor.execute(sql,['王二麻子3',age])
connection_oracle.commit()#提交操作!!!!!!!!!!!!!!!!!!!不提交数据库不更新
cursor.close()
connection_oracle.close()
删除操作
del_sql = 'delete from table1 where 姓名 = :name'
cursor.execute(del_sql,['张三'])
更新操作,修改
update_sql = 'update table1 set 年龄 =:age where 姓名 =:name '
cursor.execute(update_sql,[100,'李四'])