LoginSignup
0
0

[備忘録]PythonからOracleDatabaseへ接続する

Posted at

はじめに

*備忘録なので荒いです
WindowsからOracleDBへアクセスする際に、手軽にexeからアクセスできるようにする

InstantClientは下記よりダウンロードしておく

スクリプト

Pythonスクリプト

import oracledb
import os

def get_oracle_info(dsn, user, password):
    try:
        # Oracleデータベースへの接続
        connection = oracledb.connect(user=user, password=password, dsn=dsn)
        cursor = connection.cursor()

        # Oracleのバージョン取得
        cursor.execute("SELECT * FROM v$version")
        version = cursor.fetchone()[0]

        # データベース名取得
        cursor.execute("SELECT sys_context('userenv', 'db_name') FROM dual")
        db_name = cursor.fetchone()[0]

        cursor.close()
        connection.close()

        return version, db_name

    except oracledb.DatabaseError as e:
        print(f"An error occurred: {e}")
        return None, None

def read_config(file_path):
    config = {}
    with open(file_path, 'r') as file:
        for line in file:
            key, value = line.strip().split('=')
            config[key] = value
    return config

if __name__ == "__main__":
    # 設定ファイルのパス
    config_file = 'config.txt'
    
    if not os.path.exists(config_file):
        print(f"Configuration file '{config_file}' not found.")
        exit(1)
    
    config = read_config(config_file)

    dsn = config.get('dsn')
    user = config.get('user')
    password = config.get('password')

    oracledb.init_oracle_client()
    version, db_name = get_oracle_info(dsn, user, password)

    if version and db_name:
        print(f"Oracle Database Version: {version}")
        print(f"Database Name: {db_name}")
    else:
        print("Failed to retrieve database information.")

    input("Press Enter to exit...")

pyinstallerのspecファイル

pyinstallerでexe化

  • Oracle Instant Clientは別途インストールしておく
# -*- mode: python ; coding: utf-8 -*-


a = Analysis(
    ['oracledb_select2.py'],
    pathex=[],
    binaries=[
        ('C:/path/to/instantclient-basiclite-windows.x64-19.23.0.0.0dbru/instantclient_19_23/*.dll', '.')
    ],
    datas=[],
    hiddenimports=['secrets', 'asyncio', 'uuid'],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=[],
    noarchive=False,
    optimize=0,
)
pyz = PYZ(a.pure)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.datas,
    [],
    name='oracledb_select',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

exe化

pyinstaller.exe --upx-dir C:\path\to\upx-3.96-win64  .\oracledb_select3.spec

upxを指定してあげることでexeの圧縮に繋がる

ConfigFile

config.txt

dsn=[host]:1521/[service]
user=testuser
password=WelCome123#123#

完成されたexeファイルと同じ階層にconfigファイルを置くことでで実行が可能になる

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0