Python Forum
How can I add some data from file.txt to db.sqlite3 ?
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I add some data from file.txt to db.sqlite3 ?
#1
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
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic SQL query using Py: Inserting or querying sqlite3 database not returning data marlonbown 3 1,307 Nov-08-2022, 07:16 PM
Last Post: marlonbown
  xml file creation from an XML file template and data from an excel file naji_python 1 2,071 Dec-21-2020, 03:24 PM
Last Post: Gribouillis
  how do i store then call a mp3 from sqlite3 .db file gr3yali3n 3 5,638 Dec-11-2020, 10:28 AM
Last Post: snippsat
  Adding data to a table in SQLite3 djwilson0495 2 3,001 Aug-15-2020, 02:48 PM
Last Post: djwilson0495
  Find data using a period of time in SQLITE3 SmukasPlays 2 2,145 Jul-30-2020, 02:02 PM
Last Post: SmukasPlays
  Deleting data in SQlite3 SmukasPlays 0 1,429 Jul-25-2020, 02:07 PM
Last Post: SmukasPlays
  sqlite3 database does not save data across restarting the program SheeppOSU 1 3,405 Jul-24-2020, 05:53 AM
Last Post: SheeppOSU
  ZIP file in Sqlite3 database chesschaser 4 3,426 Jul-23-2020, 09:53 PM
Last Post: chesschaser
  How to save CSV file data into the Azure Data Lake Storage Gen2 table? Mangesh121 0 2,080 Jun-26-2020, 11:59 AM
Last Post: Mangesh121
  Deleting data in sqlite3 JJ39 3 2,438 Jun-23-2019, 04:39 PM
Last Post: noisefloor

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020