ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python中try子句的语法错误无效

2019-11-09 02:14:45  阅读:11  来源: 互联网

标签:google-cloud-platform python mysql



首先,我很抱歉如果格式设置不正确,我之前从未在这里提出过任何问题.

我在win10-64上的virtualenv中运行python 2.7.15.我正在尝试将一些测试字符串上载到MySQL数据库,但是却出现了最愚蠢的错误,而且我不知道该如何解决. MySQL Python / Connector应该正确安装.与GCP SDK相同.

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")

cursor = cnx.cursor()

# Test information
id = str(1)
testtitle = str("Look a fake title")
teststring = str('thislistis representingaveryshort pdfwithfuckedup spaces')

add_pdf = ("INSERT INTO pdftexttest (id, title, text) VALUES (%s, %s, %s)", (id, testtitle, teststring)

try:
  cursor.execute(add_pdf)
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_BAD_TABLE_ERROR:
    print("no pdf for you")
  else:
    print(err)
    print("here")

cnx.commit()

cursor.close()
cnx.close()

运行此代码后,我得到

(env) C:\Users\USER\Google Drive\Summer Education\ProjPdf2Txt>python TXT2SQL.py
  File "TXT2SQL.py", line 47
    try:
      ^
SyntaxError: invalid syntax

我以前有使用Java的经验,但我仍然是新手程序员.

如果删除Try … Except子句并直接进入cursor.execute(),控制台会告诉我

(env) C:\Users\USER\Google Drive\Summer Education\ProjPdf2Txt>python TXT2SQL.py
  File "TXT2SQL.py", line 46
    cursor.execute(add_pdf)
         ^
SyntaxError: invalid syntax

解决方法:

您在这里缺少括号.

add_pdf =(“将INSERT INTO pdftexttest(ID,标题,文本)VALUES(%s,%s,%s)”,(id,testtitle,teststring))



标签:google-cloud-platform,python,mysql

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有