Warm tip: This article is reproduced from serverfault.com, please click

create a table if not exist in sqlite3 python using variable

发布于 2020-11-28 17:16:31

I am trying to create a new table in sqlite3 database for each name I get from my entry widget in tkinter i don't know how to do it here username is variable for entry widget get

Questioner
AADITYA JAIN
Viewed
0
Barmar 2020-11-29 01:19:34

Two problems:

  1. The CREATE TABLE syntax doesn't have a VALUES clause. You just put the table name there.
  2. Placeholders can only be used where an expression is allowed, they can't be used to substitute table and column names.

You have to use string formatting.

cursr.execute(f"""CREATE TABLE IF NOT EXISTS {username} (
    site_name TEXT,
    user_id TEXT,
    user_password TEXT)""")

As an aside, creating a table for each user is probably a poor design. Dynamic data should be in table data, not table and column names. Why not just have a single table user_sites like this:

CREATE TABLE user_sites (
    username TEXT,
    site_name TEXT,
    user_id TEXT,
    user_password TEXT)