根据变量创建SQL表

时间:2019-02-23 13:54:05

标签: python sqlite

我正在创建一个包含3个主表的数据库:

用户,分配,组

与其他与表“组”相关的潜在表。这些潜在的表应是根据“组”表中的键变量命名的表。例如,如果Groups表中的条目具有groupName =“ Group_One”,我想创建一个名为“ Group_One”的表,然后将其他用户的用户名存储到该表中。如您所见,没有一种在“组”表的一行中存储多个用户名的实用方法。

这是我正在测试以尝试实现此代码的代码:

import sqlite3

def Database_Setup():
    Cur.executescript(
                        """
                        CREATE TABLE IF NOT EXISTS USERS
                        (
                        username text,
                        password text,
                        clearance int,
                        classes int
                        );
                        CREATE TABLE IF NOT EXISTS GROUPS 
                        (
                        groupName text
                        teacher text,
                        teachingAssistant text
                        users
                        );
                        CREATE TABLE IF NOT EXISTS ASSIGNMENTS
                        (
                        assignmentID int,
                        assignmentName text,
                        assignmentInfo text,
                        dueDate date,
                        setDate date,
                        completedAmount int
                        )
                        """
                        )
def Potential_Solution():
    Group_Name = "Group1"
    List_Of_Users = ["User1","User2","User3"]
    Cur.execute("""
                      CREATE TABLE IF NOT EXISTS {}
                      (
                      username text,
                      randomVar text
                      )
                      """.format(Group_Name))
                      # This part works fine ^^
    for User in List_Of_Users:
        Cur.execute("INSERT INTO TABLE ? values (?,'Some_Var')",(Group_Name,User))

def Main():
    Database_Setup()
    Potential_Solution()
    Cur.execute("SELECT * FROM Group1")
    print(Cur.fetchall())

if __name__ == "__main__":
    Conn = sqlite3.connect("FOO_DB.db")
    Cur = Conn.cursor()
    Main()

但是,当我执行此操作时,会遇到此错误:

Traceback (most recent call last):
  File "E:/Python/Py_Proj/DB LIST vs new db example.py", line 53, in <module>
    Main()
  File "E:/Python/Py_Proj/DB LIST vs new db example.py", line 46, in Main
    Potential_Solution()
  File "E:/Python/Py_Proj/DB LIST vs new db example.py", line 42, in Potential_Solution
    Cur.execute("INSERT INTO TABLE ? values (?,Some_Var)",(Group_Name,User))
sqlite3.OperationalError: near "TABLE": syntax error

是否有可行的方法来完成我要实现的目标?还是应该采用另一种方法?

1 个答案:

答案 0 :(得分:2)

I tried the following , 
you have to remove TABLE keyword use positional formatting 
Cur.execute("INSERT INTO {0} VALUES('{1}', 'SomeVar')".format(Group_Name,User )
                )

import sqlite3

def Database_Setup():
    Cur.executescript(
                        """
                        CREATE TABLE IF NOT EXISTS USERS
                        (
                        username text,
                        password text,
                        clearance int,
                        classes int
                        );
                        CREATE TABLE IF NOT EXISTS GROUPS 
                        (
                        groupName text
                        teacher text,
                        teachingAssistant text
                        users
                        );
                        CREATE TABLE IF NOT EXISTS ASSIGNMENTS
                        (
                        assignmentID int,
                        assignmentName text,
                        assignmentInfo text,
                        dueDate date,
                        setDate date,
                        completedAmount int
                        )
                        """
                        )
def Potential_Solution():
    Group_Name = "Group1"
    List_Of_Users = ["User1","User2","User3"]
    Cur.execute("""
                      CREATE TABLE IF NOT EXISTS {}
                      (
                      username text,
                      randomVar text
                      )
                      """.format(Group_Name))
    for User in List_Of_Users:
        Cur.execute("INSERT INTO {0} VALUES('{1}', 'SomeVar')".format(Group_Name,User )
                    )





def Main():
    Database_Setup()
    Potential_Solution()
    Cur.execute("SELECT * FROM Group1")
    print(Cur.fetchall())

if __name__ == "__main__":
    Conn = sqlite3.connect("FOO_DB.db")
    Cur = Conn.cursor()
    Main()