Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

python 3.x - Printing sql query results

Two separate but related questions to querying a database and sending the results to discord:

Example code:

async def query(ctx):
try:
    cursor.execute("SELECT record.name, COUNT(place.name) .....")
        for row in cursor:
        await ctx.send(row)
except Error as e:
     print(e)

Each row prints as it's own message and displays in the following format:

('potato', 1)
('orange', 1)
('steak', 1)

I would like to append all the rows into a single message as the results are numerous enough that this blows the channel up with spam messages. Each row on it's own line and part 2, remove the query result formatting.

It should look like this(parentheses indicating one message not visible formatting):

"
potato 1
orange 2
steak 1
"

I have tried to change "await ctx.send(row)" to "await ctx.send(row[0],row[1]) to remove the formatting but I know send doesn't operate in the same manner as print() and it's instead looking for a string. "await ctx.send(row[0].join(row[1]))" fails because: "TypeError: can only join an iterable"

Further I have no clue how to get the result from cursor append it into a single string with line breaks.

Thanks in advance for any advice.

question from:https://stackoverflow.com/questions/65891156/printing-sql-query-results

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is just basic python

message = ""
for veg, i in cursor.fetchall(): # Or however you named it
    message += f"{veg} {i}
"

The message var now looks like this:

"potato 1
orange 2
steak 1"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...