windows下python怎么链接数据库

2024-05-08

1. windows下python怎么链接数据库

一,安装MySQL-python
python 连接mysql数据库需要 Python interface to Mysql包,包名为
MySQL-python
,PyPI上现在到了1.2.5版本。MySQL-python在windows下是通过.exe文件的installer安装的,
前提是已经安装的python需要写入注册表,参考这篇文章:windows安装python2.7后的注册(registry)问题。
然后开始安装MySQL-python,不过这里有个坑,从PyPI上下载的MySQL-python版本--
MySQL-python-1.2.5.win32-py2.7.exe (md5)--不一定能用,原因是python环境和MySQL-python在软件位数上可能不一致,
比如,我本地安装的python是64位,从PyPI上下载的MySQL-python就没法使用,
会报这样的错误: python ImportError: DLL load failed: %1
只要安装正确位数的MySQL-python就可以了,这里分享下64位的:
MySQL-python-1.2.5.win-amd64-py2.7.exe

二,简单使用
参考代码如下:
Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win32import MySQLdbconn = MySQLdb.connect(host='localhost',port=3306,user='root',passwd='123456',db='test')cur = conn.cursor()cur.execute('select `title`, `text` from `entries` limit 10')2Lcur.fetchall()(('bokeyuan', 'bokeyuan text...'), ('google translate', 'google translate text...'))cur.close()conn.close()

windows下python怎么链接数据库