Python3从数据库取数并存入变量的方法及代码问题排查
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 tocur.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 assignedfetch_pswd = cur.execute(...), butexecute()doesn't return the query results — it returns eitherNoneor the number of rows affected (depending on the database driver). The actual results are retrieved viacur.fetchall()(orfetchone()), 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
USERIDcolumn 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, sofetch_pswdwill 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()whereconnis your active database connection) and that you haven't accidentally closed the connection before running this query.
内容的提问来源于stack exchange,提问作者Rajesh Prasad

