TransWikia.com

Parameterized SQLite Table Insertion via Python?

Stack Overflow Asked on December 22, 2021

I have been trying to get a function working to insert a name in to table of users, but for some reason it just isn’t working.

import sqlite3

def CreateUser(Name):
    try:
        sqliteConnection = sqlite3.connect('Expenses.db')
        cursor = sqliteConnection.cursor()
        make_user = """INSERT INTO Users (Name) VALUES(?);"""
        cursor.execute(make_user, Name)
        sqliteConnection.commit()
        print()
        print('User Successfully Created')
        print()
        # cursor.close()
    except sqlite3.Error as error:
            print('Failed to Create User', error)
            print()
    finally:
            if (sqliteConnection):
                sqliteConnection.close()
                print()
                escape = input('Press any key to continue.')


Name = input('> ')
CreateUser(Name)

But for some reason it takes the input string and converts it to the sum of every letter in the string. Inputting a name that is a single digit or letter works, but as soon as it’s two or more letters, it throws an error of having too many bindings.

I have tried several variations but I just can’t seem to get it working. Can anyone point me in the right direction?

One Answer

Try binding a tuple containing the name, instead of passing the name variable directly:

sqliteConnection = sqlite3.connect('Expenses.db')
cursor = sqliteConnection.cursor()
make_user = """INSERT INTO Users (Name) VALUES(?);"""
cursor.execute(make_user, (Name,))    # change is here
sqliteConnection.commit()

Answered by Tim Biegeleisen on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP