在cursor.execute函数()中使用变量

2024-09-28 20:48:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试作为一个项目,为数据库管理提供一个基于基本菜单的Python程序。但是,在使用cursor.execute()函数时,我陷入了困境——参数中有一个变量。 这是密码(请原谅我的混乱):

elif choose == 4:
cursor = convar.cursor()
con = True
name = str(input("Enter name of table: "))
str1 = 'create table {} '.format(name)
str2 = ''
print("Enter table details. ")
con = True
str2 = ''
while con == True:
    col = str(input("Enter name of column: "))
    typ = str(input("Enter data type of column: "))

    command = '{} {}(255)'.format(col, typ)
    str2 = str2 + command 
    
    conti = str(input("Do you wish to create more columns? "))
    if conti == 'Yes' or conti == 'yes':
        str2 = str2 + ', '
    elif conti == 'no' or conti == 'No':
        str2 = '(' + str2 + ')'
        con = False
    else:
        pass

cursor.execute ('create table {} {}'.format(name, str2))

这部分代码旨在创建表,同时允许用户指定表的名称和列的数据类型 这是通过将所有用户输入存储为一个字符串来完成的,最后,将字符串与cursor.execute()函数一起使用

但是每当我运行这段代码时,我都会得到一个错误。 我不确定错误是因为语法不正确,还是因为某个无法在cursor.execute()中使用变量

欢迎任何建议


Tags: of函数nametrueformatinputexecutecreate