Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Dynamic INSERT to SQLite

import csv
import sqlite3

#Give the table a name and use it for the file as well
table_name = 'Example'
a = open(table_name + '.csv', 'r')

#Use a dict reader
my_reader = csv.DictReader(a)
print my_reader.fieldnames # Use this to create table and get number of field values,etc.

# create statement
create_sql = 'CREATE TABLE ' + table_name + '(' + ','.join(my_reader.fieldnames) + ')'
print create_sql

#open the db
conn = sqlite3.connect('example.db')
c = conn.cursor()
# Create table using field names
c.execute(create_sql)
insert_sql = 'insert into ' + table_name + ' (' + ','.join(my_reader.fieldnames) + ') VALUES (' + ','.join(['?'] * len(my_reader.fieldnames))+ ')'
print insert_sql

values = []
for row in my_reader:
    row_values = []
    for field in my_reader.fieldnames:
        row_values.append(row[field])
    values.append(row_values)

c.executemany(insert_sql, values)
Comment

PREVIOUS NEXT
Code Example
Python :: how do i access individual elements of matrix in python? 
Python :: object get in djangi 
Python :: lxml etree fromstring find 
Python :: django assign authenticated user to foreign user 
Python :: What is the right way to do such import 
Python :: sklearn encoding pipelin 
Python :: Not getting values from Select Fields with jQuery 
Python :: Creating 2-dimesional array 
Python :: how to make a typing effect in python 
Python :: django add list to manytomany 
Python :: replace dataframe column element if element is within a specific list 
Python :: clear notebook output 
Python :: ring Creating a Multi-Dimensional Array using List 
Python :: update specific field in index in elastic using python 
Python :: list slicing 
Python :: notebook prevent cell output 
Python :: void setup and void loop 
Python :: Use of OfficeApi 
Python :: create a separate dataframe with the columns 
Python :: Can Selenium python Web driver helps to extract data from DB 
Python :: how to read then overwrite a file with python with truncate 
Python :: legend outside subplot not displayed 
Python :: django amzon like app 
Python :: pattern program in python A aB bCc DdEe 
Python :: how to add multiple commands to tkinter button 
Python :: how to set time limit for receiving data in socket python 
Python :: how make aloop in python 
Python :: how to read comment before the root element of xml python 
Python :: numpy add to same index multiple times 
Python :: python slicing string 
ADD CONTENT
Topic
Content
Source link
Name
7+8 =