You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3从数据库取数并存入变量的方法及代码问题排查

Fixing Your Python Database Data Retrieval Issue

Hey Rajesh, let's break down why your code isn't storing the password from your database into the fetch_pswd variable. There are two critical mistakes in your snippet that are causing this problem:

Key Issues in Your Code

  • Incorrect parameter formatting for execute()
    When passing a single parameter to cur.execute(), you used (lg_id) — but in Python, this isn't treated as a tuple. It's just the variable wrapped in parentheses. To create a single-element tuple (which the database driver expects for parameterized queries), you need to add a trailing comma: (lg_id,). Without this comma, the database can't map your input correctly to the ? placeholder.

  • Not capturing the query result
    You assigned fetch_pswd = cur.execute(...), but execute() doesn't return the query results — it returns either None or the number of rows affected (depending on the database driver). The actual results are retrieved via cur.fetchall() (or fetchone()), but you're not assigning that result to your variable.

Corrected Code Example

Here's how to fix both issues:

if lg_id in list_user_id:
    # Use a proper single-element tuple for the parameter
    cur.execute("SELECT PASSWORD FROM REGISTER WHERE USERID = ?", (lg_id,))
    # Assign the query result to your variable
    fetch_pswd = cur.fetchall()
    
    # Optional: If you only expect one password (since USERID is likely unique)
    # Use fetchone() to get a single record, then extract the password string
    # fetch_pswd = cur.fetchone()[0]

Quick Notes

  • fetchall() returns a list of tuples, even if there's only one result. For example, it might look like [('your_password_here',)].
  • If your USERID column is unique (which it should be for a user registry), fetchone() is more efficient — it retrieves just the first matching record. Adding [0] extracts the password string directly from the tuple, so fetch_pswd will hold the actual password value instead of a tuple.
  • Double-check that your database connection and cursor are properly initialized (e.g., cur = conn.cursor() where conn is your active database connection) and that you haven't accidentally closed the connection before running this query.

内容的提问来源于stack exchange,提问作者Rajesh Prasad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:56:03