2016-08-04 49 views
0

我試圖在python腳本中使用mysqldb。db.close上的Synax錯誤()

這裏是代碼的從腳本

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

林gettig上db.close一個錯誤()

一部分 「db.close() ^ 語法錯誤:無效的語法」

那麼這裏有什麼建議?

+0

縮進?它應該縮進到'try:'' – Owen

+5

'你在'try'之後忘記'except'。 –

+0

這些是你使用的真實報價嗎?反引號... – erip

回答

2

如果沒有except,則不能使用try

忽略所有的錯誤正確的方法是這樣的:

​​
+0

'db.close'應該處於'finally'嗎? – erip

1

錯誤與嘗試: - 它尋找一個不同的是:在db.close之前。

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 
$ 

這是告訴你缺少的只是在你的榜樣條款。

這不是您報告的錯誤,也許您的語法錯誤是您未包含在您的問題中的部分代碼。

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