gpt4 book ai didi

Python:在没有 MySQLdb 模块的情况下访问 MySQL 数据库

转载 作者:行者123 更新时间:2023-11-28 19:51:50 25 4
gpt4 key购买 nike

是否有另一种方法可以使用与 Mac OS 10.5.x 捆绑在一起的 Python (2.5.1) 版本中包含的内容连接到 MySQL 数据库?不幸的是,我无法将 MySQLdb 模块添加到我正在使用的客户端机器上......我需要使用 Leopard 附带的 Python 的库存版本。

最佳答案

为什么不安装 MySQLdb 的用户(非系统)副本?这些是 the files你需要安装:

/usr/lib/pyshared/python2.6
/usr/lib/pyshared/python2.6/_mysql.so
/usr/share/pyshared
/usr/share/pyshared/MySQLdb
/usr/share/pyshared/MySQLdb/constants
/usr/share/pyshared/MySQLdb/constants/CLIENT.py
/usr/share/pyshared/MySQLdb/constants/REFRESH.py
/usr/share/pyshared/MySQLdb/constants/FLAG.py
/usr/share/pyshared/MySQLdb/constants/FIELD_TYPE.py
/usr/share/pyshared/MySQLdb/constants/__init__.py
/usr/share/pyshared/MySQLdb/constants/ER.py
/usr/share/pyshared/MySQLdb/constants/CR.py
/usr/share/pyshared/MySQLdb/__init__.py
/usr/share/pyshared/MySQLdb/cursors.py
/usr/share/pyshared/MySQLdb/times.py
/usr/share/pyshared/MySQLdb/connections.py
/usr/share/pyshared/MySQLdb/converters.py
/usr/share/pyshared/MySQLdb/release.py
/usr/share/pyshared/_mysql_exceptions.py

即使您无法安装到/usr/lib 和/usr/share/pyshared,您也可以将它安装在其他任何地方,只要它位于客户端 PYTHONPATH 中列出的目录中即可。

如果出于某种原因安装 MySQLdb 的用户副本不是一个选项,那么您可以执行以下操作,但要注意:由于我在下面列出的原因,这是与 mysqld 交互的可怕方式:

打开一个终端并输入类似的内容

mysql -u USER -pPASSWORD -D DATABASE -Bse "select * from table;"

-B tells mysql to run in "batch" mode
-s tells mysql to run in "silent" mode
-e tells mysql to execute the following statement

如果这可行,那么您可以使用 python 的 subprocess 模块来调用 mysql 命令(例如上面的命令)。

例如,

import subprocess
user='xxxxxx'
password='xxxxxxxx'
database='xxxxxxxx'
cmd=['mysql', '-u', user, '-p%s'%password, '-D', database, '-Bse', "select * from table;"]
proc=subprocess.Popen(cmd,stdout=subprocess.PIPE)
retval=proc.communicate()[0]
print(retval)

如上所述,这样做你会损失很多。即,

<醇>
  • retval 只是一个巨大的字符串。您会丢失有关字段和记录开始和结束位置的所有信息,
  • 你失去了到 Python 数据类型的自动转换,
  • 您丢失了信息性错误异常。
  • 关于Python:在没有 MySQLdb 模块的情况下访问 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2313307/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com