Saurabh Adhikary Saurabh Adhikary - 1 year ago 110
Python Question

Create Custom Column name in sqlite table in Python

I want to create a table in SQLite with Python where the column names will be stored in a variable.

import sqlite3 as lite<br>
con = lite.connect('MyData.db')

name = raw_input() # I am taking values from user here
id1 = raw_input()
a=con.execute("CREATE TABLE PROD_SA_U_1(
name TEXT,
ids INT")

Instead of the column being named as "name","id" , I want what the user inputs.

Answer Source

You could simply substitute the names the user provides in the query string.


import sqlite3 as lite
con = lite.connect('MyData.db')

field_1 = raw_input()
field_2 = raw_input()

query = "CREATE TABLE PROD_SA_U_1( %s TEXT, %s INT)"

a = con.execute(query % (field_1, field_2))

However, note that this approach is vulnurable to running incorrect queries if the fields are not validated, so you should sanitise the fields before passing them further. For example, a malicious user might pass a Drop database query within your arguments.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download