首页  >  文章  >  后端开发  >  使用 Python 通过 ODBC 或 JDBC 访问 IRIS 数据库

使用 Python 通过 ODBC 或 JDBC 访问 IRIS 数据库

Linda Hamilton
Linda Hamilton原创
2024-09-29 06:14:02116浏览

Access IRIS database with ODBC or JDBC using Python

字符串问题

我正在使用 Python 通过 JDBC(或 ODBC)访问 IRIS 数据库。 我想将数据提取到 pandas 数据框中来操作数据并从中创建图表。我在使用 JDBC 时遇到了字符串处理问题。这篇文章旨在帮助其他人遇到同样的问题。 或者,如果有更简单的方法来解决这个问题,请在评论中告诉我!

我使用的是 OSX,所以我不确定我的问题有多独特。我正在使用 Jupyter Notebooks,尽管如果您使用任何其他 Python 程序或框架,代码通常是相同的。

JDBC 问题

当我从数据库中获取数据时,列描述任何字符串数据都会作为数据类型java.lang.String返回。如果打印字符串数据,它将看起来像:“(p,a,i,n,i,n,t,h,e,r,e,a,r)”而不是预期的“painintherear”。

这可能是因为当使用 JDBC 获取时,数据类型 java.lang.String 的字符串作为可迭代对象或数组传入。 如果您使用的 Python-Java 桥接器(例如 JayDeBeApi、JDBC)未一步自动将 java.lang.String 转换为 Python str,则可能会发生这种情况。

相比之下,Python 的 str 字符串表示形式将整个字符串作为一个单元。 当 Python 检索普通 str(例如通过 ODBC)时,它不会拆分为单个字符。

JDBC 解决方案

要解决此问题,您必须确保 java.lang.String 正确转换为 Python 的 str 类型。 您可以在处理获取的数据时显式处理此转换,因此它不会被解释为可迭代或字符列表。

有很多方法可以进行字符串操作;这就是我所做的。

import pandas as pd

import pyodbc

import jaydebeapi
import jpype

def my_function(jdbc_used)

    # Some other code to create the connection goes here

    cursor.execute(query_string)

    if jdbc_used:
        # Fetch the results, convert java.lang.String in the data to Python str
        # (java.lang.String is returned "(p,a,i,n,i,n,t,h,e,r,e,a,r)" Convert to str type "painintherear"
        results = []
        for row in cursor.fetchall():
            converted_row = [str(item) if isinstance(item, jpype.java.lang.String) else item for item in row]
            results.append(converted_row)

        # Get the column names and ensure they are Python strings 
        column_names = [str(col[0]) for col in cursor.description]

        # Create the dataframe
        df = pd.DataFrame.from_records(results, columns=column_names)

        # Check the results
        print(df.head().to_string())

    else:  
        # I was also testing ODBC
        # For very large result sets get results in chunks using cursor.fetchmany(). or fetchall()
        results = cursor.fetchall()
        # Get the column names
        column_names = [column[0] for column in cursor.description]
        # Create the dataframe
        df = pd.DataFrame.from_records(results, columns=column_names)

    # Do stuff with your dataframe

ODBC 问题

使用 ODBC 连接时,不会返回字符串或不返回字符串。

如果您要连接到包含 Unicode 数据(例如,不同语言的名称)的数据库,或者您的应用程序需要存储或检索非 ASCII 字符,则必须确保数据在数据库之间传递时保持正确编码。数据库和您的 Python 应用程序。

ODBC 解决方案

此代码确保在向数据库发送和检索数据时,使用 UTF-8 对字符串数据进行编码和解码。 在处理非 ASCII 字符或确保与 Unicode 数据的兼容性时,这一点尤其重要。

def create_connection(connection_string, password):
    connection = None

    try:
        # print(f"Connecting to {connection_string}")
        connection = pyodbc.connect(connection_string + ";PWD=" + password)

        # Ensure strings are read correctly
        connection.setdecoding(pyodbc.SQL_CHAR, encoding="utf8")
        connection.setdecoding(pyodbc.SQL_WCHAR, encoding="utf8")
        connection.setencoding(encoding="utf8")

    except pyodbc.Error as e:
        print(f"The error '{e}' occurred")

    return connection

connection.setdecoding(pyodbc.SQL_CHAR,encoding="utf8")

告诉 pyodbc 在获取 SQL_CHAR 类型(通常是固定长度字符字段)时如何从数据库中解码字符数据。

connection.setdecoding(pyodbc.SQL_WCHAR,encoding="utf8")

设置 SQL_WCHAR、宽字符类型(即 Unicode 字符串,例如 SQL Server 中的 NVARCHAR 或 NCHAR)的解码。

connection.setencoding(encoding="utf8")

确保从 Python 发送到数据库的任何字符串或字符数据都将使用 UTF-8 进行编码,
这意味着Python在与数据库通信时会将其内部str类型(即Unicode)转换为UTF-8字节。


把它们放在一起

安装 JDBC

安装JAVA - 使用dmg

https://www.oracle.com/middleeast/java/technologies/downloads/#jdk23-mac

更新 shell 以设置默认版本

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    23 (arm64) "Oracle Corporation" - "Java SE 23" /Library/Java/JavaVirtualMachines/jdk-23.jdk/Contents/Home
    1.8.421.09 (arm64) "Oracle Corporation" - "Java" /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
/Library/Java/JavaVirtualMachines/jdk-23.jdk/Contents/Home
$ echo $SHELL
/opt/homebrew/bin/bash
$ vi ~/.bash_profile

将 JAVA_HOME 添加到您的路径

export JAVA_HOME=$(/usr/libexec/java_home -v 23)
export PATH=$JAVA_HOME/bin:$PATH

获取 JDBC 驱动程序

https://intersystems-community.github.io/iris-driver-distribution/

将 jar 文件放在某个地方...我把它放在 $HOME

$ ls $HOME/*.jar
/Users/myname/intersystems-jdbc-3.8.4.jar

示例代码

它假设你已经设置了 ODBC(另一天的例子,狗吃了我的笔记......)。

注意:这是对我的真实代码的修改。请注意变量名称。

import os

import datetime
from datetime import date, time, datetime, timedelta

import pandas as pd
import pyodbc

import jaydebeapi
import jpype

def jdbc_create_connection(jdbc_url, jdbc_username, jdbc_password):

    # Path to JDBC driver
    jdbc_driver_path = '/Users/yourname/intersystems-jdbc-3.8.4.jar'

    # Ensure JAVA_HOME is set
    os.environ['JAVA_HOME']='/Library/Java/JavaVirtualMachines/jdk-23.jdk/Contents/Home'
    os.environ['CLASSPATH'] = jdbc_driver_path

    # Start the JVM (if not already running)
    if not jpype.isJVMStarted():
        jpype.startJVM(jpype.getDefaultJVMPath(), classpath=[jdbc_driver_path])

    # Connect to the database
    connection = None

    try:
        connection = jaydebeapi.connect("com.intersystems.jdbc.IRISDriver",
                                  jdbc_url,
                                  [jdbc_username, jdbc_password],
                                  jdbc_driver_path)
        print("Connection successful")
    except Exception as e:
        print(f"An error occurred: {e}")

    return connection


def odbc_create_connection(connection_string):
    connection = None

    try:
        # print(f"Connecting to {connection_string}")
        connection = pyodbc.connect(connection_string)

        # Ensure strings are read correctly
        connection.setdecoding(pyodbc.SQL_CHAR, encoding="utf8")
        connection.setdecoding(pyodbc.SQL_WCHAR, encoding="utf8")
        connection.setencoding(encoding="utf8")

    except pyodbc.Error as e:
        print(f"The error '{e}' occurred")

    return connection

# Parameters

odbc_driver = "InterSystems ODBC"
odbc_host = "your_host"
odbc_port = "51773"
odbc_namespace = "your_namespace"
odbc_username = "username"
odbc_password = "password"

jdbc_host = "your_host"
jdbc_port = "51773"
jdbc_namespace = "your_namespace"
jdbc_username = "username"
jdbc_password = "password"

# Create connection and create charts

jdbc_used = True

if jdbc_used:
    print("Using JDBC")
    jdbc_url = f"jdbc:IRIS://{jdbc_host}:{jdbc_port}/{jdbc_namespace}?useUnicode=true&characterEncoding=UTF-8"
    connection = jdbc_create_connection(jdbc_url, jdbc_username, jdbc_password)
else:
    print("Using ODBC")
    connection_string = f"Driver={odbc_driver};Host={odbc_host};Port={odbc_port};Database={odbc_namespace};UID={odbc_username};PWD={odbc_password}"
    connection = odbc_create_connection(connection_string)


if connection is None:
    print("Unable to connect to IRIS")
    exit()

cursor = connection.cursor()

site = "SAMPLE"
table_name = "your.TableNAME"

desired_columns = [
    "RunDate",
    "ActiveUsersCount",
    "EpisodeCountEmergency",
    "EpisodeCountInpatient",
    "EpisodeCountOutpatient",
    "EpisodeCountTotal",
    "AppointmentCount",
    "PrintCountTotal",
    "site",
]

# Construct the column selection part of the query
column_selection = ", ".join(desired_columns)

query_string = f"SELECT {column_selection} FROM {table_name} WHERE Site = '{site}'"

print(query_string)
cursor.execute(query_string)

if jdbc_used:
    # Fetch the results
    results = []
    for row in cursor.fetchall():
        converted_row = [str(item) if isinstance(item, jpype.java.lang.String) else item for item in row]
        results.append(converted_row)

    # Get the column names and ensure they are Python strings (java.lang.String is returned "(p,a,i,n,i,n,t,h,e,a,r,s,e)"
    column_names = [str(col[0]) for col in cursor.description]

    # Create the dataframe
    df = pd.DataFrame.from_records(results, columns=column_names)
    print(df.head().to_string())
else:
    # For very large result sets get results in chunks using cursor.fetchmany(). or fetchall()
    results = cursor.fetchall()
    # Get the column names
    column_names = [column[0] for column in cursor.description]
    # Create the dataframe
    df = pd.DataFrame.from_records(results, columns=column_names)

    print(df.head().to_string())

# # Build charts for a site
# cf.build_7_day_rolling_average_chart(site, cursor, jdbc_used)

cursor.close()
connection.close()

# Shutdown the JVM (if you started it)
# jpype.shutdownJVM()

以上是使用 Python 通过 ODBC 或 JDBC 访问 IRIS 数据库的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn