Python Database Select Query
Select Query in Python
Processing the result of a select query is different from the other DML statements. While execution, DML statements return number of rows affected, executing a select query returns the rows fetched by the query.
CODE/PROGRAM/EXAMPLE
import cx_Oracle
con = cx_Oracle.Connection('user/pswd@192.168.2.1/john')
cur = cx_Oracle.Cursor(con)
cur.execute(“SELECT * FROM Computer”)
for row in cur: #Iterating return value of query row by row
print(row)
cur.close()
con.close()
The return value of a select query is a list of rows and we can iterate row by row. Each row is represented as a tuple.
The column values retrieved from the query are converted from the Oracle data types to their equivalent Python datatypes. For example, Varchar2 is converted automatically to string in Python.
Demo
Try out the code and observe the results.
CODE/PROGRAM/EXAMPLE
import cx_Oracle
con = cx_Oracle.Connection('user/pswd@192.168.2.1/john')
cur = cx_Oracle.Cursor(con)
cur.execute(“SELECT * FROM Computer”)
for row in cur:
print(row)
cur.close()
con.close()