Any other way to import data files(like .csv) in python sqlite3 module ? [not insert one by one]

前端 未结 1 1404
星月不相逢
星月不相逢 2021-02-06 14:04

In sqlite3\'s client CLI, there is \" .import file TABLE_name \" to do it.

But, I do not want to install sqlite3 to my server at present.

In python sqlite3 modul

相关标签:
1条回答
  • 2021-02-06 14:37

    You could insert at one shot using executemany command instead of inserting one by one

    Lets say I have users.csv with following contents

    "Hugo","Boss"
    "Calvin","Klein"
    

    and basically open with csv module and pass it to .executemany function

    import csv,sqlite3
    
    persons= csv.reader(open("users.csv"))
    con = sqlite3.connect(":memory:")
    
    con.execute("create table person(firstname, lastname)")
    con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
    
    for row in con.execute("select firstname, lastname from person"):
        print row
    
    #(u'Hugo', u'Boss')
    #(u'Calvin', u'Klein')
    
    0 讨论(0)
提交回复
热议问题