有没有办法以不同的方式做第三和第四个实例中的事情,这是行不通的

Is there a way to do what is in the third and fourth instance in a different way this doesn't work

该代码是关于员工薪资管理的,但我们也在尝试通过不要求用户输入正确的语法而只输入值(例如在 create table 中)来自动化某些代码陈述。

import mysql.connector as mysql
while True: 
print("1.C&L")
print("2.Cursor Define")
print("3.Create Table")
print("4.Insert Data into Table")
a=int(input("Enter Choice(0 to exit)"))
if a==0:
    break
if a==1:
     db=mysql.connect(
         host='localhost',
         user='root',
         passwd='12345',
         database='opip'
     ) 
     print(db)   
if a==2:
    curs=db.cursor()
    print(curs)
if a==3:
    print("CREATE TABLE [table_name] ([column_name] [data_type][data_size])")
    z=input("Type the above syntax with correct variables")
    curs.execute(z)

if a==4:
    x="""INSERT into opip(id,Name,Age,DOB,Position,Salary)VALUES(%s,%s,%s,%s,%s,%s)"""
    data=input("Provide Values") 
    curs.execute(x,data)
    db.commit()

您可以通过两种方式完成此操作

  1. 递归读取每个占位符的输入 [table_name]、[column_name]、[data_type]、[data_size]直到读取到您确定的结束标志。

     table=input("Table Name ")
     columnName=input("Column Name ")
     columnType=input("Column Data Type ")
     columnSize=input("Column Size ")
    
  2. 读取单个输入中的所有内容,然后将其拆分为相应的类型以填充您的模板

     txt = input()
     values = txt.split()
     dbString = "CREATE TABLE " + values[0] + "(" # Start Syntax
    
     i=1
     while i < len(values):
         dbString += values[i] + " " # Column Name
         i += 1
    
         dbString += values[i] + "(" # Column Data Type
         i += 1
    
         dbString += values[i] + ")" # Column Size
         i += 1
    
         if i < len(values):
           dbString += ", " # prepare for next column details
    
     dbString += ")" # End Syntax
    
     curs.execute(dbString) # Execute Dynamic SQL
    

对于输入

mytable col1 char 2 col2 char 3

DbString 输出

CREATE TABLE mytable(col1 char(2), col2 char(3))