Python and SQLite: insert into table

后端 未结 6 559
梦如初夏
梦如初夏 2020-12-08 00:08

I have a list that has 3 rows each representing a table row:

>>> print list
[laks,444,M]
[kam,445,M]
[kam,445,M]

How to insert thi

相关标签:
6条回答
  • 2020-12-08 00:48

    Adapted from http://docs.python.org/library/sqlite3.html:

    # Larger example
    for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
              ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
              ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
             ]:
        c.execute('insert into stocks values (?,?,?,?,?)', t)
    
    0 讨论(0)
  • 2020-12-08 00:56
    conn = sqlite3.connect('/path/to/your/sqlite_file.db')
    c = conn.cursor()
    for item in my_list:
      c.execute('insert into tablename values (?,?,?)', item)
    
    0 讨论(0)
  • 2020-12-08 01:01

    This will work for a multiple row df having the dataframe as df with the same name of the columns in the df as the db.

    tuples = list(df.itertuples(index=False, name=None))
    
    columns_list = df.columns.tolist()
    marks = ['?' for _ in columns_list]
    columns_list = f'({(",".join(columns_list))})'
    marks = f'({(",".join(marks))})'
    
    table_name = 'whateveryouwant'
    
    c.executemany(f'INSERT OR REPLACE INTO {table_name}{columns_list} VALUES {marks}', tuples)
    conn.commit()
    
    0 讨论(0)
  • 2020-12-08 01:05

    there's a better way

    # Larger example
    rows = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
            ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
            ('2006-04-06', 'SELL', 'IBM', 500, 53.00)]
    c.executemany('insert into stocks values (?,?,?,?,?)', rows)
    connection.commit()
    
    0 讨论(0)
  • 2020-12-08 01:06

    Not a direct answer, but here is a function to insert a row with column-value pairs into sqlite table:

    def sqlite_insert(conn, table, row):
        cols = ', '.join('"{}"'.format(col) for col in row.keys())
        vals = ', '.join(':{}'.format(col) for col in row.keys())
        sql = 'INSERT INTO "{0}" ({1}) VALUES ({2})'.format(table, cols, vals)
        conn.cursor().execute(sql, row)
        conn.commit()
    

    Example of use:

    sqlite_insert(conn, 'stocks', {
            'created_at': '2016-04-17',
            'type': 'BUY',
            'amount': 500,
            'price': 45.00})
    

    Note, that table name and column names should be validated beforehand.

    0 讨论(0)
  • 2020-12-08 01:06
    #The Best way is to use `fStrings` (very easy and powerful in python3)   
    #Format: f'your-string'   
    #For Example:
    
    mylist=['laks',444,'M']
    
    cursor.execute(f'INSERT INTO mytable VALUES ("{mylist[0]}","{mylist[1]}","{mylist[2]}")')
    
    #THATS ALL!! EASY!!
    #You can use it with for loop!
    
    0 讨论(0)
提交回复
热议问题