python - 如何在 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 " )
解决方案
在 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 注入。
推荐阅读
- ios - 当推送通知到来时播放自定义声音并播放直到用户与应用交互
- android - 如何使一个 Activitly 正确地观察 Lifecycle 事件
- javascript - 为什么“this”在回调函数中变为空?
- android - 来自 Google 的 Fiftness 历史 API 的值错误
- python - plotly:TypeError:无法将字典更新序列元素#0转换为序列
- php - xampp 不工作,当我尝试启动我的服务器时出现错误
- c++ - 如何从向量构造整数值
C++ 中的值 - alfresco - 标题上的 UTF-8 土耳其语字符
- mysql - 无论记录是否存在,获取两个日期之间的最小余额
- azure - Azure:在 Azure Web 应用程序的 Linux 容器中运行非 Web 应用程序