【问题标题】:Error MySql You have an error in your SQL syntax. when adding a parameter with a variable错误 MySql 您的 SQL 语法有错误。添加带有变量的参数时
【发布时间】:2019-05-08 08:03:22
【问题描述】:

使用 textBox1.Text 添加参数时出现语法错误。我想向数据库添加一列。我该怎么做才对。请写出正确的代码

private async void button1_Click(object sender, EventArgs e)
{      
    MySqlCommand command = new MySqlCommand("ALTER TABLE Students ADD COLUMN ? TEXT", sqlConnection);

    command.Parameters.AddWithValue("?", textBox1.Text); 

    try
    {
        await command.ExecuteNonQueryAsync();
        Close();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

}

截图https://i.paste.pics/77ce28a6fd93598b0939bc43a1d15b9a.png

截图2结果回答https://i.paste.pics/a9e8c0739bcbaf6cf7a23ca62a9c9812.png

【问题讨论】:

  • 这根本不是 C。你是说 C++ 吗?
  • 您不能使用参数作为对象名称(表和列)
  • '?' 是列的合法名称吗?
  • @Broman C# 我可能在某处犯了错误

标签: c# mysql sql


【解决方案1】:

参数不能用于修改列名或表名。您必须手动构建查询。但不要忘记转义用户输入,以避免 sql 注入:

string escapedStringColumnName = MySql.Data.MySqlClient.MySqlHelper.EscapeString(textBox1.Text);

// Do some more validations, what text you got before building you column..
if (!new Regex("[a-zA-z ]+").IsMatch(escapedStringColumnName))
    throw new Exception();

MySqlCommand command = new MySqlCommand("ALTER TABLE Students ADD COLUMN `" + escapedStringColumnName + "` TEXT", sqlConnection);

【讨论】:

  • 您不能选择带有空格的列名。尝试“asdasd”而不是“asd asd”。
  • 我需要带空格,创建一个列。例如,列名将是“第二天”
  • 您可以使用` 引用列名。我修改了示例以使其与空格一起使用。但请注意:空格会带来问题。你必须每次都引用..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 2013-02-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多