简体   繁体   中英

Is there a better way to work with SQLite3 “SELECT” query results in Python3?

When making a "SELECT" query to my SQLite3 db I'm finding it quite cumbersome to do something as simple as reach into the db and grab a value and have it look exactly as it does in my program as it does in the db. I'm not familiar enough to know if this is just how it is or if there's a better way I should be doing these kinds of things.

The first element of this is in regards to the fact that something like this:

player_name = c.execute("""SELECT name FROM players WHERE pid = ?""", (pid,))
print(player_name)

will yield something like this:

<sqlite3.Cursor object at 0x10c185110>

The only way I've found to extract the actual content is by iterating over the resulting cursor and storing the content inside a list:

player_name = []
sql = c.execute("""SELECT name FROM players WHERE pid = ?""", (pid,))
for result in sql:
    player_name.append(result)
    player_name = str(player_name).replace("[", "").replace("]", "")

The other element is less of issue but I figured I'd throw it out there. It's the fact that each result from my above example comes out looking like this:

 >>> print(player_name)
 ('Ben Johnson',)

In the end, to get the exact string out of the db and into my program I'm doing this for each query:

>>> player_name = []
>>> sql = c.execute("""SELECT name FROM players WHERE pid = ?""", (pid,))
>>> for result in sql:
>>>     player_name.append(result)
>>>     player_name = str(player_name).replace("[", "").replace("]", "")
>>>     player_name = str(player_name).replace("('", "").replace("',)", "")
>>> 
>>> print(player_name)

Ben Johnson

The cursor object returned by execute contains a list of rows (actually, they are computed on demand); you are indeed supposed to iterate over the cursor with for or something like that.

Each row is a tuple that contains all column values. To get the first column, just do row[0] :

for row in c.execute("SELECT SomeColumn FROM ..."):
    print(row[0])

If you want to get a single column value from a single row, you can write a helper function:

def query_single_value(db, query, *parameters):
    cursor = db.execute(query, parameters)
    for row in cursor:
        return row[0]
    else:
        return None  # not found

print(query_single_value(c, "SELECT name FROM players WHERE pid = ?", pid))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM