Mac下python连接mysql数据库

时间:2023-03-08 20:06:01

一、下载Mysql官方connector驱动 
地址:https://dev.mysql.com/downloads/connector/python/ 
根据提示安装.dmg文件即可。 
二、验证是否安装成功

shell> python
>>> from distutils.sysconfig import get_python_lib >>> print get_python_lib() # Python v2.x
/Library/Python/2.7/site-packages >>> print(get_python_lib()) # Python v3.x
/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

三、使用示例代码测试连接数据库

import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
cnx.close()
  • 1
  • 2
  • 3
  • 4
  • 5

也可使用如下命令测试是否安装成功:

~ python
>>> import mysql.connector as mc
>>> mc.__version__
'2.1.6'
  • 1
  • 2
  • 3
  • 4

更多使用方式可访问官方网站: 
https://dev.mysql.com/doc/connector-python/en/connector-python-example-connecting.html

四、其它驱动连接方式 
1.MySQL-Python(或者说MySQLdb)相关链接 
http://blog.****.net/zhaoteng345/article/details/52165914 
http://blog.****.net/janronehoo/article/details/25207825 
https://www.zhihu.com/question/30963225 
https://www.runoob.com/python/python-mysql.html 
2. Python中最连接Mysql常用的驱动是

mysql-python :mysql的C语言的驱动 
mysql-connector:msql官方的驱动 
pymysql:python语言的驱动