Python' TypeError:没有足够的格式字符串参数'何时运行mysql查询

时间:2016-04-19 16:02:51

标签: python mysql

我有一张名为“作者'在数据库' menagerie'。有两列Id和photo.Id是INT,照片是BLOB。当我尝试将图像存储到mysql数据库表时我得到错误

TypeError: not enough arguments for format string

我的完整代码是

import MySQLdb

conn = MySQLdb.connect("localhost","root","rset","menagerie" )
cursor = conn.cursor()


def read_file(filename):
  with open(filename, 'rb') as f:
      photo = f.read()
  return photo

def update_blob(author_id, filename):
  # read file
  data = read_file(filename)

  # prepare update query and data
  query = "UPDATE authors SET photo = %s WHERE id  = %s"

  #query blob data form the authors table
  cursor.execute(query, (author_id,))
  photo = cursor.fetchone()[0]
  cursor.close()
  conn.close()

def main():
 update_blob(1,"d:/Emmanu/project-data/bc1.jpg")

if __name__ == '__main__':
main()

1 个答案:

答案 0 :(得分:0)

尝试以下更改

query = "UPDATE authors SET photo = %s WHERE id  = %s"
cursor.execute(query, (data, author_id))

%s是一个占位符,它被转换为SQL文本以处理正确的转义(并避免SQL注入)。

不确定您尝试使用.format(data, author_id)做什么,然后在原始author_id来电中提供execute作为单项元组,但请查看建议的更改是否适合您

通过这些更改,您最终会得到

import MySQLdb

conn = MySQLdb.connect("localhost","root","rset","menagerie" )
cursor = conn.cursor()


def read_file(filename):
    with open(filename, 'rb') as f:
        photo = f.read()
    return photo

def update_blob(author_id, filename):
    # read file
    data = read_file(filename)

    # prepare update query and data
    query = "UPDATE authors SET photo = %s WHERE id  = %s"

    #query blob data form the authors table
    cursor.execute(query, (data, author_id))
    cursor.close()
    conn.close()

def main():
     update_blob(1,"d:/Emmanu/project-data/bc1.jpg")

if __name__ == '__main__':
    main()