db.close()上的Synax错误

时间:2016-08-04 11:49:10

标签: python mysql-python

我试图在python脚本中使用mysqldb。

以下是脚本

中代码的一部分
cursor = db.cursor()

    sql = """INSERT INTO location(`name`, `lat`, `long`, `guid`, `image`, `date`)VALUES(%(name)s, %(lat)s, %(long)s, %(guid)s, %(image)s, %(date)s)"""

    try:
        cursor.execute(sql)
        db.commit()

db.close()

我在db.close()

上犯了错误

" db.close()      ^     SyntaxError:语法无效"

那么这里有什么建议吗?

4 个答案:

答案 0 :(得分:2)

如果没有try,则无法使用except

忽略所有错误的正确方法是:

try:
    cursor.execute(sql)
    db.commit()
except:
    pass

db.close()

答案 1 :(得分:1)

错误在于try: - 它在db.close之前查找except:

答案 2 :(得分:0)

如果发布完整的工作示例,您会让每个人都更轻松。 我在帖子中添加了一些虚拟代码以使其运行

class fake:
    def commit(self,):pass
    def execute(self,sql):pass
    def close(self,):pass


db =fake()
cursor=fake()

if 1:
    sql = """INSERT INTO location(`name`, `lat`, `long`, `guid`, `image`, `date`)VALUES(%(name)s, %(lat)s, %(long)s, %(guid)s, %(image)s, %(date)s)"""

    try:
        cursor.execute(sql)
        db.commit()

db.close()

如果我跑这个,我得到:

$ python3 test.py 
  File "test.py", line 17
    db.close()
    ^
IndentationError: unexpected unindent
$ 

显示您缺少示例中的except子句。

这不是您报告的错误,也许您的语法错误属于您未在问题中包含的代码的一部分。

答案 3 :(得分:0)

忽略代码中的缩进错误,您需要使用except子句,finally子句或两者都使用try语句。

使用finally子句可以确保数据库连接已关闭:

try:
    cursor.execute(sql)
    db.commit()
finally:
    db.close()

在实践中,值得包括except子句,以便记录异常:

import traceback

try:
    cursor.execute(sql)
    db.commit()
except Exception as exc:
    traceback.print_exc()    # or whatever logging you require
    raise                    # optionally re-raise the exception
finally:
    db.close()               # _always_ executed