首页 > 解决方案 > 如何在 python 中添加占位符以在 mysql 数据库中创建表名?

问题描述

在这里,我想根据用户的意愿命名表名,但我帮不上忙

** 我已包含此代码用于将 Python 连接到数据库 **

import mysql.connector
from mysql.connector.abstracts import MySQLCursorAbstract
mydb= mysql.connector.connect(host="localhost",user="root",passwd="",database="python")
mycursor = mydb.cursor()`

print("do you want to build  table")

g=input()

if(g=='yes'or g=='YES'):

    print("please enter table name")

    enter code here

    k=input()

    mycursor.execute("create table " )

标签: pythonmysqlsqlmysql-connector

解决方案


在 mySql 中创建表的语法如下所示:

CREATE TABLE my_table_name (my_first_column INT);

这将创建名为“my_table_name”的表,其中有一列名为“my_first_column”,类型为整数。

要实现这一点,您可以使用字符串格式

mycursor.execute("CREATE TABLE {} (my_first_column INT)".format(k))

或者,如果您使用 >Python3.7,您可以使用方便的 f-strings

mycursor.execute(f"CREATE TABLE {k} (my_first_column INT)")

您还应该考虑清理用户输入k以禁止 SQL 注入。


推荐阅读