1

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.

1 Answer 1

1

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

Example:

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@SaurabhAdhikary Cool. Don't forget to accept the answer if your query was resolved :)
Sure, slight change , for INT we will use %d. Anyway , Ty for ya help, solved my purpose. Pls upvote my question too. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.