简体   繁体   中英

Python: Convert List to String Items

I'm trying to insert data into SQL

This is a simple concept of the code:

# Establish Connection to SQL Database
connection = sqlite3.connect("MyDatabase.db")
cursor = connection.cursor()

sql = "INSERT INTO Table_Expenses VALUES DB_QMarks"

data = ['40', '50', '10']

# Execute SQL Query
cursor.execute(sql, data)

When I execute this it returns an error:

Expected: ("1", "2020-01-04", "40", "50", "10")

Actual Outcome: ("1", "2020-01-04", ['40','50','10'])

DB_QMarks is code ran previously that creates a "(?)" for each object in the data list. The data variable is appended to from user input therefore there is no determinant of the length. I have code already that creates "(?)" for each object. This isn't the problem, the problem is removing the square brackets from the outcome of data so that it works correctly in the cursor.execute function.

The error returns "The current statement uses 5 bindings, there are only 3 supplied". How can I convert the list to the expected string with no brackets. I tried converting to a string but it replaces the brackets with double quotes (") and the same problem happens.

Thank you

sql_output = ("1", "2020-01-04", ['40','50','10'])
# further processing into string as requested
string_output = ""
for x_val in sql_output:
    if type(x_val) == list:
        for val in x_val:
            string_output += "'" + str(val) + "' "
    else:
        string_output += "'" + str(x_val) + "' "
print(string_output)

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