尝试将文本框内容插入我的数据库 C# 时出错

Error trying to insert textbox contents into my database C#

我正在尝试将文本框的内容放入我的 table 名为 [Questions Space] 但 QuestionText":",connect);带有下划线的错误提示

Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.

Invalid expression term ',' and ')'

我似乎找不到解决这个问题的地方我确信解决方案并不难,但我是新手。

string QuestionText = QuestionBox.Text;

SqlCommand command5 = new SqlCommand("INSERT INTO Questions ([Question Space]) VALUES ({0})"QuestionText,connect);

我也试过了,但也没用:

 SqlCommand command5 = new SqlCommand("INSERT INTO Questions ([Question Space]) VALUES ({0})"QuestionText,connect);

如有任何帮助,我将不胜感激。

如果有人想看的话,这是我的按钮的完整代码:

  private void button1_Click(object sender, EventArgs e)
    {


        string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
        SqlConnection connect = new SqlConnection(connectionString);
        connect.Open();

        int checkedradiobutton = 0;


        if(radioButton1.Checked)
        {
            checkedradiobutton = 1;

        }
        else if(radioButton2.Checked)
        {
            checkedradiobutton = 2;
        }
        else if(radioButton3.Checked)
        {
            checkedradiobutton = 3;
        }



        switch (checkedradiobutton)
        {
            case 0: MessageBox.Show("Please select a question type");
                break;
            case 1: 
                SqlCommand command1 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (1)",connect);
                command1.ExecuteNonQuery();
                break;


            case 2:

                SqlCommand command2 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (2)",connect);
                command2.ExecuteNonQuery();
                break;
            case 3: 

                SqlCommand command3 = new SqlCommand("INSERT INTO Questions ([Question Type]) VALUES (3)",connect);
                command3.ExecuteNonQuery();
                break;

        }




        string QuestionText = QuestionBox.Text;

        SqlCommand command5 = new SqlCommand("INSERT INTO Questions ([Question Space]) VALUES ("QuestionText")",connect);

        command5.ExecuteNonQuery();




    }

应该是这样的:String.Format("INSERT INTO Questions ([Question Space]) VALUES ('{0}')",QuestionText)

您缺少文本插入语句周围的单引号,并且您的 sql 出现类似于

INSERT INTO Questions([Question Space]) VALUES (This is the question text)

应该是下面的,

SqlCommand command5 = new SqlCommand("INSERT INTO Questions ([Question Space]) VALUES ('" + QuestionText + "')",connect);

话虽如此,您不应该使用这种创建命令文本的机制。您应该使用命令参数来降低 SQL 注入

的风险

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters%28v=vs.110%29.aspx

这还将处理您的值中的单引号。

下面的例子:

SqlCommand command5 = new SqlCommand("INSERT INTO Questions ([Question Space]) VALUES (@QuestionText)",connect);

command5.Parameters.AddWithValue("@QuestionText", QuestionText);
command5.ExecuteNonQuery();