1

Syntax error when adding a parameter with textBox1.Text.I want to add a column to the database. How do I do it right. Write the correct code please

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);
    }

}

Screenshot https://i.paste.pics/77ce28a6fd93598b0939bc43a1d15b9a.png

Screenshot 2 result answer https://i.paste.pics/a9e8c0739bcbaf6cf7a23ca62a9c9812.png

4
  • 1
    This is not C at all. Did you mean C++? Commented May 8, 2019 at 8:08
  • 1
    you can't use parameter for object name (table and columns) Commented May 8, 2019 at 8:09
  • Is '?' a legal name for a column? Commented May 8, 2019 at 8:09
  • @Broman C# I just could have made a mistake somewhere Commented May 8, 2019 at 9:55

1 Answer 1

1

Parameters can't be used to modify column- or table-names. You have to build your query manually. But don't forget to escape the user-input, to avoid sql-injections:

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);
Sign up to request clarification or add additional context in comments.

4 Comments

You're not allowed to select a columnname with spaces. Try "asdasd" instead of "asd asd".
I need with spaces, create a column. For example, the column name will be "Next day"
You can quote columnnames with `. I modified the example to make it work with spaces. But be aware: Spaces can bring up problems. You have to quote every time ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.