有没有一种方法将Python连接到Db2数据库?
pip install ibm_db
from ibm_db import connect
# Careful with the punctuation here - we have 3 arguments.
# The first is a big string with semicolons in it.
# (Strings separated by only whitespace, newlines included,
# are automatically joined together, in case you didn't know.)
# The last two are emptry strings.
connection = connect('DATABASE=<database name>;'
'HOSTNAME=<database ip>;' # 127.0.0.1 or localhost works if it's local
'PORT=<database port>;'
'PROTOCOL=TCPIP;'
'UID=<database username>;'
'PWD=<username password>;', '', '')
ibm_db
的命令实际上并不会直接给你结果。相反,你需要重复调用命令上的一个fetch
方法来获取结果。我编写了这个辅助函数来处理这个问题。def results(command):
from ibm_db import fetch_assoc
ret = []
result = fetch_assoc(command)
while result:
# This builds a list in memory. Theoretically, if there's a lot of rows,
# we could run out of memory. In practice, I've never had that happen.
# If it's ever a problem, you could use
# yield result
# Then this function would become a generator. You lose the ability to access
# results by index or slice them or whatever, but you retain
# the ability to iterate on them.
ret.append(result)
result = fetch_assoc(command)
return ret # Ditch this line if you choose to use a generator.
from ibm_db import tables
t = results(tables(connection))
from ibm_db import exec_immediate
sql = 'LIST * FROM ' + t[170]['TABLE_NAME'] # Using our list of tables t from before...
rows = results(exec_immediate(connection, sql))
rows
包含了你的数据库中第170个表中的一系列行,其中每一行都包含了一个 dict
,其键为列名,值为对应的值。经过大量的搜索,我发现了如何使用ibm_db连接到DB2。
首先,如果您使用的是高于3.2版本的Python,则使用
pip install ibm_db==2.0.8a
版本2.0.8(最新版本)将安装失败。
然后使用以下内容进行连接
import ibm_db_dbi as db
conn = db.connect("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username;PWD=password;", "", "")
使用
for t in conn.tables():
print(t)
使用此功能可以执行SQL语句
cursor = conn.cursor()
cursor.execute("SELECT * FROM Schema.Table")
for r in cursor.fetchall():
print(r)
查看此链接以获取官方的不太准确文件。
ibm-db是Python和Django的官方DB2驱动程序,可以在这里找到:
这里有一篇最近的Ubuntu Linux安装教程:
我应该提到,旧版本还有几个非官方的DB2 Python驱动程序,但是你应该使用ibm-db。
除了 @prof1990 的回答外:
从 2.0.9 版本开始(2018年8月16日),即使使用 Python 3,您也可以简单地使用以下命令:
pip install ibm_db
参考资料:
https://github.com/ibmdb/python-ibmdb#updated-ibm_db
连接示例在这里:
import ibm_db
ibm_db.connect("DATABASE=<dbname>;HOSTNAME=<host>;PORT=<60000>;PROTOCOL=TCPIP;UID=<username>;PWD=<password>;", "", "")
完整的API文档在这里:
import jaydebeapi
conn_src = jaydebeapi.connect(
'com.ibm.db2.jcc.DB2Driver',
['YourHostName:PortNo/DatabaseName','userid','password'],'C:/db2jcc4.jar'
)
cursor=conn_src.cursor()
sql = 'Select * from schemaname.TableName fetch first 100 rows only '
cursor.execute(sql)
print("fetchall:")
result = cursor.fetchall()
for r in result:
print(r)
有一种方法可以仅使用Python请求库连接到IBM db2。对我有效。
步骤1:
进入IBM CLOUD仪表板 ->导航到您的IBM db2实例 ->单击“服务凭据”
应该有一个默认的,如果没有,请创建一个。此服务凭证是一个字典。复制服务凭证。
步骤2:
db2id = { // service credential dictionary here //}
api = "/dbapi/v3"
host = db2id['https_url']+api
userinfo = {"userid":db2id['username'],"password":db2id['password']}
service = '/auth/tokens'
r = requests.post(host+service,json=userinfo)
access_token = r.json()['token']
auth_header = {"Authorization": "Bearer "+access_token}
// Connection to database established
第三步
现在您可以运行SELECT,INSERT,DELETE,UPDATE查询
INSERT,DELETE,UPDATE查询的格式相同。 在INSERT,DELETE,UPDATE查询之后,必须发送COMMIT查询,否则更改不会反映出来。(即使没有更改也应该提交更改)
插入/更新/删除查询
sql = " your insert/update/delete query here "
sql_command = {"commands":sql,"limit":1000,"separator":";","stop_on_error":"yes"}
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)
sql_command = {"commands":"COMMIT","limit":1000,"separator":";","stop_on_error":"yes"}
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)
sql = " your select query here "
service = "/sql_jobs"
r = requests.post(host+service,headers=auth_header,json=sql_command)
jobid = r.json()['id']
r = requests.get(host+service+"/"+jobid,headers=auth_header)
results = r.json()['results']
rows = results[0]['rows']
变量行会有您查询的结果。您可以根据需要使用它。
我没有使用任何DDL查询。但我认为它们应该像DML查询一样工作。虽然不确定!
有很多种方式可以从Python连接到Db2。我试图提供一份选项概要。请注意,在许多环境中,现在强制执行SSL/TLS,这需要额外的参数(见下文)。
Db2没有提供一个,而是四个Python驱动程序(客户端)。 Db2文档页面“针对IBM数据库服务器的Python、SQLAlchemy和Django Framework应用程序开发” 提供了关于这四个驱动程序的很好的概述:
典型的连接信息由Db2服务器(主机名)、端口、数据库名称和用户名/密码信息组成。如果没有指定其他内容,则大多数驱动程序假定连接未加密。因此,要通过加密连接进行连接,需要更多的参数。它们取决于Db2版本、Db2产品类型和其他一些因素。让我们从简单的开始。
新版本的Db2简化了SSL/TLS的使用,因为证书现在已经包含在软件包中。一个典型的连接字符串将如下所示:
conn_str='database=MYDB;hostname=db2host.example.com;port=50001;protocol=tcpip;uid=db2inst1;pwd=secret;security=SSL'
ibm_db_conn = ibm_db.connect(conn_str,'','')
IBM的Db2适用于各种平台。如果您正在尝试连接到运行在IBM i服务器(以前称为AS/400、iSeries或System i)上的Db2,则需要使用名为Db2 Connect的产品,而这相当昂贵。大多数使用Python连接到Db2 for i的人使用ODBC(通常通过PyODBC)。
我不完全确定Db2在其z(主机)服务器上的情况,但我认为它也需要Db2 Connect。
pip install ibm-db
时,出现了以下错误:pip install ibm-db
running build_ext
building 'ibm_db' extension
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
----------------------------------------
ERROR: Failed building wheel for ibm-db
Failed to build ibm-db
ERROR: Could not build wheels for ibm-db, which is required to install pyproject.toml-based projects.
query_str = "SELECT COUNT(*) FROM table_name"
conn = ibm_db.pconnect("dsn=write","usrname","secret")
query_stmt = ibm_db.prepare(conn, query_str)
ibm_db.execute(query_stmt)
ibm_db
库? - ArtOfWarfarepip install ibm_db
- Soumendra
SQLCODE=-104
意味着您有一个非法符号或标记。我建议您在之前的行上打印(print)sql
,然后将该输出复制并粘贴到另一个评论中,以便您自己找出问题所在。 - ArtOfWarfare