我试图将文本框的内容放入我的名为[Questions Space]的表中,但是QuestionText“:”,connect);标有
错误的下划线只有赋值,调用,递增,递减,等待和新对象表达式才能用作语句。
和
无效的表达式术语','和')'
我似乎无法找到解决这个问题的任何地方我确信解决方案并不困难,但我是新手。
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();
}
答案 0 :(得分:2)
应该是:String.Format("INSERT INTO Questions ([Question Space]) VALUES ('{0}')",QuestionText)
你缺少文本的insert语句周围的单引号,你的sql就像是
INSERT INTO Questions([Question Space]) VALUES (This is the question text)
答案 1 :(得分:2)
应该是以下,
SqlCommand command5 = new SqlCommand("INSERT INTO Questions ([Question Space]) VALUES ('" + QuestionText + "')",connect);
话虽如此,您不应该使用这种创建命令文本的机制。您应该使用命令参数来降低SQL注入的风险
这也将处理您的值中的单引号。
以下示例:
SqlCommand command5 = new SqlCommand("INSERT INTO Questions ([Question Space]) VALUES (@QuestionText)",connect);
command5.Parameters.AddWithValue("@QuestionText", QuestionText);
command5.ExecuteNonQuery();