Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kết nối Oracle Database trong Python


Python kết nối Oracle thông qua package cx_Oracle. Oracle là CSDL phổ biến, tính năng xử lý dữ liệu của Python được tận dụng tốt qua kết nối này. Bài viết hướng dẫn kết nối và truy vấn Oracle.

Cài đặt cx_Oracle

Dùng pip để cài đặt package kết nối.

Ví dụ

pip install cx_Oracle

Kết nối Oracle

Dùng module để kết nối qua service name. Tạo cursor, thực thi SQL tạo bảng. Xử lý try/except để bắt lỗi kết nối.

Ví dụ

import cx_Oracle

try:
    con = cx_Oracle.connect('username/password@servicename')
    cursor = con.cursor()
    # Tạo bảng
    cursor.execute("create table TableName(COL1 VARCHAR2(200), COL2 NUMBER(8))")
    print("Table Created")
except cx_Oracle.DatabaseError as e:
    print("Problem connecting to Oracle", e)
finally:
    if cursor:
        cursor.close()
    if con:
        con.close()

Kết quả:

Đầu ra

Table Created