0

0

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

心靈之曲

心靈之曲

发布时间:2024-09-29 08:03:01

|

909人浏览过

|

来源于dev.to

转载

使用 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免费学习笔记(深入)”;

相比之下,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 类型(通常是固定长度字符字段)时如何从数据库中解码字符数据。

ViaooChain 维奥连锁招商网站系统
ViaooChain 维奥连锁招商网站系统

网站功能资讯模块资料模块会员模块产品展示模块产品订购模块购物车模块留言模块在线加盟模块多级后台管理系统网站环境本系统为 asp.net开发donet版本为1.1框架数据库为acdess2000授权方式为免费,本版本本地可直接运行(使用http://localhost或http://127.0.0.1访问)如需放到外网通过域名访问,则需通过qq联系我免费索取钥匙文件,将钥匙文件放到网站空间根目录即可

下载

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开发工具
python开发工具

php中文网为大家提供各种python开发工具,好的开发工具,可帮助开发者攻克编程学习中的基础障碍,理解每一行源代码在程序执行时在计算机中的过程。php中文网还为大家带来python相关课程以及相关文章等内容,供大家免费下载使用。

772

2023.06.15

python打包成可执行文件
python打包成可执行文件

本专题为大家带来python打包成可执行文件相关的文章,大家可以免费的下载体验。

661

2023.07.20

python能做什么
python能做什么

python能做的有:可用于开发基于控制台的应用程序、多媒体部分开发、用于开发基于Web的应用程序、使用python处理数据、系统编程等等。本专题为大家提供python相关的各种文章、以及下载和课程。

764

2023.07.25

format在python中的用法
format在python中的用法

Python中的format是一种字符串格式化方法,用于将变量或值插入到字符串中的占位符位置。通过format方法,我们可以动态地构建字符串,使其包含不同值。php中文网给大家带来了相关的教程以及文章,欢迎大家前来阅读学习。

679

2023.07.31

python教程
python教程

Python已成为一门网红语言,即使是在非编程开发者当中,也掀起了一股学习的热潮。本专题为大家带来python教程的相关文章,大家可以免费体验学习。

1365

2023.08.03

python环境变量的配置
python环境变量的配置

Python是一种流行的编程语言,被广泛用于软件开发、数据分析和科学计算等领域。在安装Python之后,我们需要配置环境变量,以便在任何位置都能够访问Python的可执行文件。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

570

2023.08.04

python eval
python eval

eval函数是Python中一个非常强大的函数,它可以将字符串作为Python代码进行执行,实现动态编程的效果。然而,由于其潜在的安全风险和性能问题,需要谨慎使用。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

579

2023.08.04

scratch和python区别
scratch和python区别

scratch和python的区别:1、scratch是一种专为初学者设计的图形化编程语言,python是一种文本编程语言;2、scratch使用的是基于积木的编程语法,python采用更加传统的文本编程语法等等。本专题为大家提供scratch和python相关的文章、下载、课程内容,供大家免费下载体验。

730

2023.08.11

C++ 高级模板编程与元编程
C++ 高级模板编程与元编程

本专题深入讲解 C++ 中的高级模板编程与元编程技术,涵盖模板特化、SFINAE、模板递归、类型萃取、编译时常量与计算、C++17 的折叠表达式与变长模板参数等。通过多个实际示例,帮助开发者掌握 如何利用 C++ 模板机制编写高效、可扩展的通用代码,并提升代码的灵活性与性能。

6

2026.01.23

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
SQL 教程
SQL 教程

共61课时 | 3.5万人学习

Java 教程
Java 教程

共578课时 | 49.7万人学习

oracle知识库
oracle知识库

共0课时 | 0人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号