oracle python操作 增删改查

oracle删除

删除表内容

truncate table new_userinfo;

删除表

drop table new_userinfo;

1.首先,python链接oracle数据库需要配置好环境。

我的相关环境如下:

1)python:Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32

2)oracle:11.2.0.1.0 64bit。这个是server版本号,在链接oracle数据库的时候还需要oracle的客户端版,客户端版本的下载也要参考python的版本,python是32位的客户端下载也要用32位。

3)cx_Oracle:python链接oracle的驱动包,这个需要自己安装,https://pypi.python.org/pypi/cx_Oracle/5.3在这个网址中下载对应的驱动,下载驱动的时候一定要选好对应的版本,我的python是3.6的32位版本,所以在下载驱动的时候也要选择对应的版本,我选择的版本是cx_Oracle-5.3-11g.win32-py3.6.exe (md5),下载后直接安装运行就行了,他会有一个自检,如果没有通过就说明你的驱动版本没有下载对。

2.上面的工作做好之后,在刚才下载好的oracle客户端版本中找到下面三个文件:oci.dll、oraocci11.dll、oraociei11.dll,将这几个dll文件复制到

Python\Python36-32\Lib\site-packages文件夹中。

3.在python中输入:

1

import cx_Oracle

没有报错的话说明驱动安装成功。

4.数据库连接操作:

1

2

3

4

5

6

7

conn = cx_Oracle.connect('xzt/xzt@localhost/testdb')#这里的顺序是用户名/密码@oracleserver的ip地址/数据库名字

cur = conn.cursor()

sql = "SELECT * FROM DUAL"

cur.execute(sql)

cur.close()

conn.commit()

conn.close()

5.数据库查询:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import cx_Oracle

conn = cx_Oracle.connect('xzt/xzt@localhost/testdb')

cursor = conn.cursor ()

cursor.execute ("SELECT * FROM STUDENT_TB")

rows = cursor.fetchall() #得到所有数据集

for row in rows:

print("%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]))#python3以上版本中print()要加括号用了

print("Number of rows returned: %d" % cursor.rowcount)

cursor.execute ("SELECT * FROM STUDENT_TB")

while (True):

row = cursor.fetchone() #逐行得到数据集

if row == None:

break

print("%d, %s, %s, %s" % (row[0], row[1], row[2], row[3]))

print("Number of rows returned: %d" % cursor.rowcount)

cursor.close ()

conn.close ()

6.数据库插入:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import cx_Oracle

conn = cx_Oracle.connect('xzp/xzp@localhost/testdb')

cursor = conn.cursor()

cursor.execute ("CREATE TABLE INSERTTEST(ID INT, C1 VARCHAR(50), C2 VARCHAR(50), C3 VARCHAR(50))")

cursor.execute ("INSERT INTO INSERTTEST (ID, COL1, COL2, COL3)VALUES(1213412, 'asdfa', 'ewewe', 'sfjgsfg')")

cursor.execute ("INSERT INTO INSERTTEST (ID, COL1, COL2, COL3)VALUES(12341, 'ashdfh', 'shhsdfh', 'sghs')")

cursor.execute ("INSERT INTO INSERTTEST (ID, COL1, COL2, COL3)VALUES(123451235, 'werwerw', 'asdfaf', 'awew')")

conn.commit() #这里一定要commit才行,要不然数据是不会插入的

cursor.close()

conn.close()

上面的代码用了递归运算,循环读取彩票信息,可以一直读取到2003年第一期,由于使用的是递归,在性能上不是很好,代码非常吃内存,电脑内存不够的朋友就不要尝试了,容易死机。

参考:https://www.jb51.net/article/133972.htm