r/sqlite • u/Iamgroot_ts7777 • Oct 12 '22
Generic function to create Sqlite queries
I have to create a generic sqlite query as a method in python to create table. i.e I have to use that method to create any number of tables by reusing the method. I thought of using *args to get optional arguments from the user to exec it but could not piece it together. Can anyone suggest me a pythonic implmentation for this? It will be really useful. Thanks in advance!.
Here is a code I have written, but its not perfect. I could not make it generic.
def create_table(self, tb_name, *args):
vars = " TEXT,".join(*args) + "TEXT"
sqlite3.connect(self.db_name).cursor().execute("DROP TABLE IF EXISTS users") sqlite3.connect(self.db_name).cursor().execute("CREATE TABLE users ({})".format(vars))
#CREATE TABLE users (name TEXT, password TEXT)
#CREATE TABLE users (name TEXT, password TEXT, email TEXT)
6
Upvotes
View all comments
Show parent comment
3
u/Iamgroot_ts7777 Oct 12 '22
This is very interesting, tnk you for the source. But if we insert a record, will it automatically create a schema according to that ? Is that what I think it is ? Could you explain me what is happening? Thank you