Python Forum

Full Version: How can I add some data from file.txt to db.sqlite3 ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a subject.txt with content like this
Accidents at Home
Adoption
Advertising
Advice
Age: Youth & Old Age
Airplanes
Amusement Parks

I have a table of 'subject' in db.sqlite3
sqlite> .schema subject
CREATE TABLE "subject" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(255) NULL, "slug" varchar(255) NOT NULL UNIQUE);
sqlite>

How can I add those data from subject.txt to subject of db.sqlite3 ?

PS: I decided to use squlite3
I have just resolved it like that
def add():
    db = sqlite3.connect('../project/db.sqlite3')
    cursor = db.cursor()
    
    f = open('subject.txt')
    line = f.readline()
    while line:
        cursor.execute('''insert into subject(name, slug)
        values(:name, :slug)''',
        {'name': line.replace('&', ' and ').lower(), 'slug': formatSlug(line)})
        db.commit()
        line = f.readline()
        print(line)
    f.close() 

def formatSlug(a):
    filter = '!@%#$?\/^*(&'
    for x in filter:
        a = a.replace(x, '').replace(' ', '-')
        
    return a.lower()

add()
I think that it is not bad resolve.