一、下载cx_Oracle
pip install cx_Oracle
二、创建连接
# 第一种创建方式
conn = cx_Oracle.connect(f"{user}/{password}@{host}:{port}/{service}")
# 第二种创建方式
conn = cx_Oracle.connect(user,password, f'{host}:{port}/{service}')
三、获取游标、执行sql语句
conn = cx_Oracle.connect(f"{user}/{password}@{host}:{port}/{service}")
cursor = conn.cursor()
sql = 'select * from test'
cursor.execute(sql) # 执行sql语句
data = cursor.fetchall() # 获取所有数据
# one_data = cursor.fetchone() # 也可以获取一条数据
cursor.close() # 关闭游标
conn.close() # 关闭连接
四、插入数据
conn = cx_Oracle.connect(f"{user}/{password}@{host}:{port}/{service}")
cursor = conn.cursor()
sql = 'INSERT INTO test values (TEST_SEQ.nextval, 12)'
cursor.execute(sql) # 执行sql语句
conn.commit() # 提交
cursor.close() # 关闭游标
conn.close() # 关闭连接
注:test_seq.nextval是我创建的序列,创建序列的sql语句如下,TEST_SEQ时创建的序列名字
CREATE SEQUENCE TEST_SEQ INCREMENT BY 1 START WITH 1 NOMAXvalue NOCYCLE NOCACHE;
五、常用时间查询
# 查询距离某一个年已经过去多少年
select to_char(sysdate,'yyyy') - 1995 nowYear from dual;
# 查询年份
select '中国'||TO_CHAR(sysdate, 'yyyy') nowYear from dual;
# 查询月份
select to_char(sysdate,'mm') nowMonth from dual;
# 查询周几
SELECT TO_CHAR(sysdate-1, 'd') nowDay from dual;
# 查询几号
SELECT TO_CHAR(sysdate, 'dd') nowDay from dual;
# 查询时一年的第几周
select to_char(sysdate,'ww') from dual;
select to_char(sysdate,'iw') from dual;
SELECT to_char(sysdate, 'q') FROM dual; # 季节
SELECT TO_CHAR(SYSDATE, 'hh24') FROM dual; # 小时
SELECT TO_CHAR(SYSDATE, 'mi') FROM dual; # 分钟
SELECT TO_CHAR(SYSDATE, 'ss') FROM dual; # 秒