gpt4 book ai didi

C# - 使用变量作为 MySQL 表名

转载 作者:行者123 更新时间:2023-11-29 07:57:33 25 4
gpt4 key购买 nike

我想使用一个变量并将该值作为表名的一部分传递到 SQL 语句中,但是,我不确定我使用的方法是否安全(即使它有效)。如果没有,我该怎么办?

    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string table = "1";
MySqlCommand comm = new MySqlCommand("INSERT INTO " + table + "_tests (user_id, score, time) VALUES (@user_id, @score, @time)", conn);
comm.Parameters.Add("@user_id", MySqlDbType.VarChar);
comm.Parameters["@user_id"].Value = "2";
comm.Parameters.Add("@score", MySqlDbType.VarChar);
comm.Parameters["@score"].Value = txtScore.ToString();
comm.Parameters.Add("@time", MySqlDbType.VarChar);
comm.Parameters["@time"].Value = txtTime.ToString();

更新:

    int tableID = Convert.ToInt32(Session["TestModuleID"].ToString());
MySqlCommand comm = new MySqlCommand("INSERT INTO " + tableID.ToString() + "_tests (user_id, score, time) VALUES (@user_id, @score, @time)", conn);

最佳答案

你是对的,你所拥有的有效。正如您可能已经猜到的,您不能使用参数作为表名。

可以通过将 table 变量重新声明为整数来消除代码引发的安全问题,如下所示...

int table = 1;
MySqlCommand comm = new MySqlCommand (
"INSERT INTO " + table.ToString() +
"_tests (user_id, score, time) VALUES (@user_id, @score, @time)", conn);

这将防止任何非数字内容渗入您的查询。还有其他方法可以控制 table 变量的值。

关于C# - 使用变量作为 MySQL 表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24716389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com