Python2.7使用mysql-connector-python遇语法错误求助
解决Python 2.7连接MySQL的语法错误问题
错误原因
你遇到的SyntaxError是因为Python 2.7不支持f-string语法(该语法从Python 3.6才引入),而你安装的mysql-connector-python 8.0.32版本已放弃对Python 2.7的兼容,库内部代码使用了Python 3专属语法,导致在Python 2.7环境下运行报错。
有效解决办法
方案1:安装兼容Python 2.7的mysql-connector-python旧版本
mysql-connector-python从8.0.29版本开始不再支持Python 2.7,需安装8.0.28及更早的兼容版本:
pip install mysql-connector-python==8.0.28
安装完成后,可使用适配Python 2.7的连接代码:
import mysql.connector from mysql.connector import Error # 修改host、user、password、database的值 try: connection = mysql.connector.connect( host="127.0.0.1", user="root", password="ayyi", database="coba" ) if connection.is_connected(): print "Connected to MySQL database successfully" except Error as err: print "Error: {}".format(err) finally: if 'connection' in locals() and connection.is_connected(): connection.close() print "MySQL connection closed"
方案2:改用Python 2.7友好的MySQL连接库(推荐)
MySQL-python(对应Python 3的mysqlclient)是适配Python 2.7的稳定连接库,安装命令:
pip install MySQL-python
连接代码示例:
import MySQLdb from MySQLdb import Error try: connection = MySQLdb.connect( host="127.0.0.1", user="root", passwd="ayyi", # Python 2版本参数为passwd而非password db="coba" ) if connection: print "Connected to MySQL database successfully" except Error as err: print "Error while connecting to MySQL: {}".format(err) finally: if 'connection' in locals() and connection.open: connection.close() print "MySQL connection closed"
额外提醒
Python 2.7已于2020年1月停止官方维护,存在安全风险,若条件允许,建议优先升级到Python 3版本。
内容的提问来源于stack exchange,提问作者ayyi
相关产品推荐
相关产品推荐

