约束python函数参数

时间:2018-06-02 03:28:47

标签: python python-3.x sqlite

在python中是否有办法将函数的参数约束为仅一组值,用户应键入要更改的列的名称:

import sqlite3
def update_table(self, id: int, column_name: str, value: str):
    conn = sqlite3.connect("myDatabase.db")
    c = conn.cursor()
    c.execute("UPDATE table SET " + column_name + " = " + value +
              " WHERE id=" + id + ";")
    c.commit()
    c.close() 

id = input("Type the id: ")
c_name = input("Type the column name: ")
value = input("Type the new value: ")
update_table(id, c_name, value)

问题是如果用户输入的列名不存在,代码就会中断。限制这种选择的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

这是一个选项:

import sqlite3
def update_table(self, id: int, column_name: str, value: str):
    conn = sqlite3.connect("myDatabase.db")
    c = conn.cursor()
    c.execute("PRAGMA table_info(table_name);")
    col_names = set([col[1] for col in c.fetchall()])
    assert column_name in col_names, "{} is not a valid column name".format(column_name)
    c.execute("UPDATE table SET " + column_name + " = " + value +
              " WHERE id=" + id + ";")
    c.commit()
    c.close()
如果您在其上运行PRAGMA table_info(table_name);

fetchall将返回有关该表的信息:

[(0, 'id', 'integer', 0, None, 1),
 (1, 'one', 'varchar(10)', 0, None, 0),
 (2, 'two', 'integer', 0, None, 0)]

每个元组都描述一列,其中每列的索引1是列名。因此,我们创建了一组可能的列名来测试...