Home > Enterprise >  Convert python list object to an array
Convert python list object to an array

Time:05-17

How do i can convert python list to an array to include in mysql query? im using a mysql connector module, and got this error

Failed processing pyformat-parameters; Python 'tuple' cannot be converted to a MySQL type

im using this construction to get my values from url

from fastapi import FastAPI, Query
from typing import List


app = FastAPI()


@app.get("/myurl")
async def my_url(my_id: int = Query(...), my_type: List[int] = Query(None)):
query_inc = ("SELECT * from v_comments WHERE id=%(id)s and my_typeIN (%(my_type)s) ;")

i tried to make this type=tuple(type) but got error i\ve listed below if im not using tuple convert i got this mysql.connector.errors.ProgrammingError: Failed processing pyformat-parameters; Python 'list' cannot be converted to a MySQL type

CodePudding user response:

Try this one. In case this doesnt work, check the format in which you are supposed to send the array. (You may have to join the elements together in a string.)

Source: https://www.geeksforgeeks.org/python-convert-list-to-python-array/ Option 1:

# Python3 code to demonstrate working of
# Convert list to Python array
# Using array()   data type indicator
from array import array

# initializing list
test_list = [6, 4, 8, 9, 10]

# printing list
print("The original list : "   str(test_list))

# Convert list to Python array
# Using array()   data type indicator
res = array("i", test_list)

# Printing result
print("List after conversion to array : "   str(res))

Option 2: (In case 1st fails)

text = ['Python', 'is', 'a', 'fun', 'programming', 'language']

# join elements of text with space
print(' '.join(text))

# Output: Python is a fun programming language

CodePudding user response:

just try it:

Call tuple(list) to convert the list into a tuple object. Call str.format(tuple) to format the SQL query str with the tuple from the previous step.

my_type = tuple(type)
query_inc = ("SELECT * from v_comments WHERE id=%(id)s and my_type IN {};").format(my_type)
  • Related