Python连接到mysql错误:意外缩进

时间:2018-01-01 16:11:32

标签: python mysql database-connection mysql-python

我是Python的新手。

以下是我为在mysql表中插入行而编写的代码:

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="me",          # your username
                     passwd="mepassword",  # your password
                     db="Database")   # name of the data base
 cursor = db.cursor()

f = '[%d/%b/%Y:%I:%M:%S %z]'
now = datetime.datetime.strptime(result[1], f)

sql = (
  "INSERT INTO Database.Table (Name, Time, Number, Size, Answer) "
  "VALUES (%s, %s, %s, %d, %d,  %s)"
)
data = (result[0],now.strftime('%Y-%m-%d %H:%M:%S'),int (result[3]),int (result[4]),result[2])
cursor.execute(sql, data)
db.close()

但是当我运行此代码时,我收到错误:

File "myscript.py", line 40
    cursor = db.cursor()
    ^
IndentationError: unexpected indent

我不明白这个错误。这怎么会成为游标定义的问题?我使用默认光标定义。或者这是mysql连接的问题?问题在哪里?

1 个答案:

答案 0 :(得分:0)

试试这个:

db = MySQLdb.connect(host="localhost", user="me", passwd="mepassword", db="Database")
cursor = db.cursor()

f = '[%d/%b/%Y:%I:%M:%S %z]'
now = datetime.datetime.strptime(result[1], f)

sql = ("INSERT INTO Database.Table (Name, Time, Number, Size, Answer) " "VALUES (%s, %s, %s, %d, %d,  %s)")
data = (result[0],now.strftime('%Y-%m-%d %H:%M:%S'),int (result[3]),int (result[4]),result[2])
cursor.execute(sql, data)
db.close()

您的代码中有不正确的缩进。在python中我们不使用brackets {}, 相反,我们使用indents作为层次结构。