Thursday, August 3, 2023

Python Sqlite - Create Table With One Column and Unique and Not Null Rows, Insert List Into Column

import sqlite3

# Connect to the SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('your_database.db')

# Create a cursor object
c = conn.cursor()

# Create table
c.execute('''
    CREATE TABLE UniqueNotNullTable (
        UniqueNotNullColumn TEXT UNIQUE NOT NULL
    )
''')

# List of values to insert
values_to_insert = ['Value1', 'Value2', 'Value3']

# Insert each value from the list into the table
for value in values_to_insert:
    try:
        c.execute('''
            INSERT INTO UniqueNotNullTable (UniqueNotNullColumn) VALUES (?)
        ''', (value,))
    except sqlite3.IntegrityError:
        print(f'Value {value} already exists in the table or is null.')

# Commit the changes and close the connection
conn.commit()
conn.close()