Writing code to codes.db incorrectly
Question: I am trying to make a random code generator in python that writes to a
database. I have the codes generating and writing to the database, but instead
of adding full codes to the database it loops through letters. Here is my code
for the code generator:

    
    
    import string
    import random
    import sqlite3
    def id_generator():
        db = sqlite3.connect('codes.db')
        c = db.cursor()
        number_of_codes = 10
        stringLength = 9
        id_code = input("what letter should this begin with: \n")
        id_code = id_code.upper()
        dict_ofcodes = []
        for x in range(0, number_of_codes):
            codez = (''.join(random.choice(string.ascii_uppercase) for i in range(stringLength)))
            final_codez = (id_code + codez)
            dict_ofcodes.insert(x, final_codez)
        print (dict_ofcodes)
        dict_ofcodes_tuple = tuple(dict_ofcodes)
        print(dict_ofcodes_tuple)
        for x in range(0, number_of_codes):
            c.executemany(''' INSERT INTO codes(codes) VALUES(?)''', dict_ofcodes_tuple[x])
        db.commit()
        db.close()
    id_generator()
    

Here is what it prints

    
    
    ['AALRRIULNC', 'AZTKZBKTLK', 'ATWMWYWICO', 'AWQJIJYEJH', 'AQFIONPUNJ', 'AMJRXUIJXM', 'AUDRLSBLSG', 'ABXYXDUMPD', 'AUAXRQURBH', 'ADQEVIRDFU']
    ('AALRRIULNC', 'AZTKZBKTLK', 'ATWMWYWICO', 'AWQJIJYEJH', 'AQFIONPUNJ', 'AMJRXUIJXM', 'AUDRLSBLSG', 'ABXYXDUMPD', 'AUAXRQURBH', 'ADQEVIRDFU')
    

It writes to the database single letters of the codes: A F Y and so on

The code I used to create the schema is contained in the a python file

    
    
        import sqlite3
    
        def writeDB():
            db = sqlite3.connect('codes.db')
            c = db.cursor()
    
        # Create table
            c.execute('''CREATE TABLE codes (codes TEXT)''')
    
    
        # Save (commit) the changes
            db.commit()
    
        #can also close the connection if done with it.
        # be sure any changes have been committed or they will be lost.
            db.close()
    writeDB()
    

I created the file with the mac terminal. How could I write the full codes to
the database?


Answer: The problem is with this line:

>
>     c.executemany(''' INSERT INTO codes(codes) VALUES(?)''',
> dict_ofcodes_tuple[x])
>  

`executemany` is used to iterate over a list of parameters and call the sql
statement for each parameter. So your dict_ofcodes_tupel[x] is treated as a
character array and the INSERT is called for each character.

If you want to insert the entire string as one, use execute() instead.

>
>     c.execute(''' INSERT INTO codes(codes) VALUES(?)''',
> (dict_ofcodes_tuple[x],))
>  

or

>
>     c.execute(''' INSERT INTO codes(codes) VALUES(?)''',
> [dict_ofcodes_tuple[x]])
>  

