python - 使用 python 从查询返回元组

标签 python mysql database flask

<分区>

我目前正在使用 python 和 Flask 查询数据库。我有以下功能:`

def get_details(username):

  conn = database_connect()
  if(conn is None):
      return ERROR_CODE
  cur = conn.cursor()
  val = None

  try:
     cur.execute("""SELECT username, name, age, address
                    FROM users
                    WHERE username = %s;""",(username))

     val = cur.fetchone()
  except:
     print("failed to retrieve")

  cur.close()
  conn.close()
  return val

“用户”表中的用户名是主键,因此此查询仅返回一个元组(通过在 postgress 中手动查询确认)。然而,“val”始终是“none”。我也尝试过使用 fetchall() 但这也不起作用。

查询本身有问题吗?我应该如何编码?

最佳答案

将查询参数传递到查询中的方式存在问题。在元组中传递它们:

cur.execute("""SELECT username, name, age, address
               FROM users
               WHERE username = %s""", (username, ))
                       # comma is important HERE^

作为旁注,考虑使用 ORM 而不是直接进入数据库并手动构建 SQL 查询。有相关套餐供大家探索:flask-sqlalchemy .

关于python - 使用 python 从查询返回元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37362658/

相关文章:

python - 无法使用 SOAPpy 调用 Web 服务方法

MySQL 将字符串排序为整数,整数优先

MySQL:枚举与 Varchar-with-Index

php - 如何使用 utf8 回显像 åäö 这样的特殊字符

python - 在 Python 中使用和关闭文件

python - python 退出并删除类实例

python - Python3.1 中的 View ?

mysql - 我如何用 mysql-proxy 或任何可能的方式替换我的查询?

php - mysql 更新行(如果存在)

database - 使用 group by 子句计算行数