使用 Python 通过 ODBC 或 JDBC 访问 IRIS 数据库
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《使用 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()
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。
Win10装完系统屏幕分辨率低无法调整怎么解决
- 上一篇
- Win10装完系统屏幕分辨率低无法调整怎么解决
- 下一篇
- 如何在Lambda表达式中传递参数和返回值?
-
- 文章 · python教程 | 1小时前 |
- Python logging Formatter 统一结构化字段输出
- 185浏览 收藏
-
- 文章 · python教程 | 2小时前 | 配置 · python · Python教程 · 配置管理 Python 3.15 frozendict 不可变映射
- Python 3.15 frozendict 内置类型的配置使用场景
- 192浏览 收藏
-
- 文章 · python教程 | 5小时前 | 序列化 · python · Python pickle 进程池 multiprocessing Pool
- Python multiprocessing 进程池传递不可序列化对象
- 255浏览 收藏
-
- 文章 · python教程 | 6小时前 | 数据一致性 · Python教程 · Python 事务 自动提交 sqlite3 autocommit isolation_level
- Python sqlite3 事务模式与自动提交边界
- 197浏览 收藏
-
- 文章 · python教程 | 7小时前 |
- Python contextlib.nullcontext 统一同步异步入口
- 316浏览 收藏
-
- 文章 · python教程 | 7小时前 | 面向对象 · python · Python教程 · InitVar __post_init__ Python dataclass 派生字段 field(init=False)
- Python dataclass __post_init__ 计算派生字段
- 303浏览 收藏
-
- 文章 · python教程 | 8小时前 |
- Python typing.TypeGuard 处理复杂容器类型收窄
- 437浏览 收藏
-
- 文章 · python教程 | 10小时前 |
- Python os.fspath 支持自定义路径对象
- 214浏览 收藏
-
- 文章 · python教程 | 12小时前 | 异常处理 · 异步编程 · Python教程 · asyncio · 后台任务 任务取消 CancelledError Python asyncio asyncio.shield
- Python asyncio.shield 保护后台任务免受外层取消
- 407浏览 收藏
-
- 文章 · python教程 | 14小时前 |
- Python configparser ExtendedInterpolation 组织分层配置
- 480浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 409次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 487次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 495次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 443次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 271次使用
-
- Python sqlite3 Connection serialize 怎么导出数据库快照:备份窗口、内存占用与恢复校验
- 2026-08-26 501浏览
-
- Python监控网页状态:requests异常处理实战
- 2026-05-29 501浏览
-
- TensorFlow模型部署为API的TF Serving方法
- 2026-05-26 501浏览
-
- Python字符串编码转换:encode与decode详解
- 2026-05-16 501浏览
-
- TensorFlow裁剪无用算子方法详解
- 2026-05-15 501浏览

