Python 2.7中try子句Invalid Syntax错误排查求助
解决Python 2.7连接MySQL时的语法错误问题
嘿,我看到你在尝试把测试数据上传到GCP Cloud SQL时遇到了语法错误,咱们来一步步排查并解决它!
核心错误分析
你遇到的SyntaxError主要来自两个关键地方:
1. 导入语句的语法错误
你的第一行代码把两个导入逻辑写在了同一行,这不符合Python的语法规范:
# 错误写法 import mysql.connector from mysql.connector import errorcode
应该拆分成两行独立的导入语句:
# 正确写法 import mysql.connector from mysql.connector import errorcode
2. SQL语句与参数的定义错误
你定义add_pdf时,不仅少了一个闭合括号,还搞错了cursor.execute()的参数传递方式:
# 错误写法:缺少闭合括号,且参数传递逻辑错误 add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring)
这里的问题:
- 元组
(id, testtitle, teststring)末尾缺少一个),导致整个赋值语句结构不完整 cursor.execute()需要接收两个独立参数:SQL字符串和参数元组,你把它们打包成一个元组后,要么用解包操作符*拆分,要么直接分开定义
修正后的完整代码
下面是修复了所有语法错误,同时做了小优化的代码:
import mysql.connector from mysql.connector import errorcode # Config info will be moved into config file(s) after testing # Google Proxy Connection (Proxy must be running in shell) # C:\Users\USER\Google Drive\Summer Education\GCP # $ cloud_sql_proxy.exe -instances="pdf2txt2sql-test"=tcp:3307 config1 = { 'user': 'USER', 'password': 'PASSWORD', 'host': 'IP', 'port': '3307', 'database': 'pdftxttest', 'raise_on_warnings': True, } # Direct Connection to Google Cloud SQL config2 = { 'user': 'USER', 'password': 'PASSWORD', 'host': 'IP', 'database': 'pdftxttest', 'raise_on_warnings': True, } try: cnx = mysql.connector.connect(**config1) except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err) print("Connection not made") exit() # 连接失败后直接退出,避免后续代码调用无效连接 cursor = cnx.cursor() # Test information id = str(1) testtitle = str("Look a fake title") teststring = str('thislistis representingaveryshort pdfwithfuckedup spaces') # 推荐方式:分开定义SQL语句和参数,更直观易懂 add_pdf = "INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)" try: cursor.execute(add_pdf, (id, testtitle, teststring)) cnx.commit() print("测试数据插入成功!") except mysql.connector.Error as err: if err.errno == errorcode.ER_BAD_TABLE_ERROR: print("目标表不存在,请检查表名拼写是否正确") else: print(err) print("插入操作失败") cursor.close() cnx.close()
额外小建议
- 注意检查表名
pdftexttest和数据库中实际存在的表名完全一致(MySQL在Windows下不区分大小写,但Linux下区分,尽量保持统一) - Python 2.7已经停止官方维护了,如果后续有机会,建议升级到Python 3.x版本,能获得更好的兼容性和安全性
内容的提问来源于stack exchange,提问作者Kyle Hansen
相关产品推荐
相关产品推荐

