Python:访问没有MySQLdb模块的MySQL数据库

cit*_*cit 2 python mysql macos

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

unu*_*tbu 8

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

/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
Run Code Online (Sandbox Code Playgroud)

即使你不能安装到/ usr/lib目录和/ usr /共享/ 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
Run Code Online (Sandbox Code Playgroud)

如果这样可行,那么您可以使用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)
Run Code Online (Sandbox Code Playgroud)

如上所述,这样做会让你失去很多.也就是说,

  1. retval只是一个巨大的字符串.您将丢失有关字段和记录开始和结束位置的所有信息,
  2. 你失去了自动转换为Python数据类型,
  3. 你失去了信息错误的例外.