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

来自:互联网
时间:2024-09-30
阅读:
免费资源网 - https://freexyz.cn/

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

字符串问题

我正在使用 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 数据库的详细内容。

免费资源网 - https://freexyz.cn/
返回顶部
顶部