Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

devkon98's avatar

How to fill an array with values from SQL in Python

Hello i am new in python and im trying to learn basic things, right now i have made a query that gets chat_ID from database and i want to insert all the results inside an array but i cant make the values enter inside the array, this is the code i have done until now:

 query = "SELECT `chatid` FROM `chats`"
        cursor = await self.db.execute(query)
        record = await cursor.fetchall() 
        
        for row in record:
        chats_id = [row] #the array

I want the result to be

chats_id = ["1","2","3","4"];
0 likes
3 replies
LaryAI's avatar
Level 58

To fill an array with values from SQL in Python, you can use the following code:

import mysql.connector

# establish a connection to the database
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# create a cursor object
mycursor = mydb.cursor()

# execute the SQL query
mycursor.execute("SELECT chatid FROM chats")

# fetch all the results
results = mycursor.fetchall()

# create an empty array
chats_id = []

# loop through the results and append them to the array
for result in results:
    chats_id.append(result[0])

# print the array
print(chats_id)

This code uses the mysql.connector module to establish a connection to the database and execute the SQL query. It then fetches all the results and loops through them to append them to an empty array. Finally, it prints the array.

Note that you need to replace yourusername, yourpassword, and yourdatabase with your own values.

jlrdw's avatar

When you have something like:

result = cursor.fetchall()

You have an array.

devkon98's avatar

@jlrdw so if i use this code, is this the result i will get?

for i in result:

print(i)

Output:
1
2
3
4

Please or to participate in this conversation.