龙空技术网

Python中的Oracle数据库连接

少儿编程Prog61 170

前言:

而今兄弟们对“oracle控制台导入sql”大概比较珍视,咱们都需要了解一些“oracle控制台导入sql”的相关内容。那么小编也在网络上网罗了一些有关“oracle控制台导入sql””的相关文章,希望看官们能喜欢,我们快快来了解一下吧!

有时作为编程的一部分,我们需要使用数据库,因为我们希望存储大量的信息,所以我们使用数据库,例如Oracle、MySQL等。在本文中,我们将讨论Oracle数据库与Python的连接。这可以通过cx_Oracle模块完成。

Oracle数据库

为了让Python程序访问Oracle数据库,我们需要cx_Oracle模块做为连接器。

安装cx_Oracle

pip install cx_Oracle

通过此命令,您可以安装cx_Oracle软件包,但是必须先在PC中安装Oracle数据库。

如何使用此模块进行连接

1)导入数据库特定模块

import cx_Oracle

2)connect():现在使用connect()函数在Python程序和Oracle数据库之间建立连接。

con = cx_Oracle.connect('username/password@localhost')

3)cursor():要执行sql查询并提供结果,只需要cursor()对象。

cursor = cx_Oracle.cursor()

4)执行方法:

cursor.execute(sqlquery) – – – -> to execute single query.cursor.execute(sqlqueries) – – – -> to execute a group of multiple sqlquery seperated by “;”

5)commit():对于此查询中的DML(数据操作语言)查询,您需要执行(更新,插入,删除)操作,我们需要commit(),然后仅将结果反映在数据库中。

6)Fetch():这将检索查询结果集的下一行并返回单个序列;如果没有更多行可用,则返回None。

7)close():完成所有操作后关闭数据库。

cursor.close()con.close()

创建表:

# importing module import cx_Oracle    # Create a table in Oracle database try:       con = cx_Oracle.connect('scott/tiger@localhost')           # Now execute the sqlquery     cursor = con.cursor()           # Creating a table srollno heading which is number     cursor.execute("create table student(srollno number, \                     name varchar2(10), efees number(10, 2)")                           print("Table Created successful")       except cx_Oracle.DatabaseError as e:     print("There is a problem with Oracle", e)   # by writing finally if any error occurs # then also we can close the all database operation finally:     if cursor:         cursor.close()     if con:         con.close() 

输出:

Table Created successful

插入表:

# Program to create a table in Oracle database import cx_Oracle   try:       con = cx_Oracle.connect('scott/tiger@localhost')           # Now execute the sqlquery     cursor = con.cursor()     cursor.execute("insert into student values(19585, Niranjan Shukla, 72000")           # commit that insert the provided data     con.commit()           print("value inserted successful")   except cx_Oracle.DatabaseError as e:     print("There is a problem with Oracle", e)   # by writing finally if any error occurs # then also we can close the all database operation finally:     if cursor:         cursor.close()     if con:         con.close() 

输出:

value inserted successful

标签: #oracle控制台导入sql