mot*_*375 2 c# database sql-server sql-insert
我无法将整数值[Question Type]和字符串[Question Space]同时插入到我的数据库中同一行.每当我点击按钮并尝试执行错误时,会说:
System.Data.dll中发生了类型为"System.Data.SqlClient.SqlException"的未处理异常
附加信息:'('附近的语法不正确.
码:
SqlCommand command5 = new SqlCommand("INSERT INTO ([Question Space], [Question Type]) Questions VALUES ('@QuestionText', '@checkedradiobutton')", connect);
command5.Parameters.AddWithValue("@QuestionText", QuestionText);
command5.Parameters.AddWithValue("@checkedradiobutton", checkedradiobutton);
command5.ExecuteNonQuery();
Run Code Online (Sandbox Code Playgroud)
我很感激任何人都能给我的帮助.
如果你想看到,这是按钮的整个代码:
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;
}
string QuestionText = QuestionBox.Text;
SqlCommand command5 = new SqlCommand("INSERT INTO ([Question Space], [Question Type]) Questions VALUES ('@QuestionText', '@checkedradiobutton')", connect);
command5.Parameters.AddWithValue("@QuestionText", QuestionText);
command5.Parameters.AddWithValue("@checkedradiobutton", checkedradiobutton);
command5.ExecuteNonQuery();
}
Run Code Online (Sandbox Code Playgroud)
和我的数据库表:
CREATE TABLE [dbo].[Questions]
(
[QuestionID] INT IDENTITY (1, 1) NOT NULL,
[Actual answer] NVARCHAR (50) NULL,
[Question Space] NVARCHAR (50) NULL,
[Question Type] INT NULL,
PRIMARY KEY CLUSTERED ([QuestionID] ASC)
);
Run Code Online (Sandbox Code Playgroud)
INSERT INTO的正确语法是
INSERT INTO <table> (field1, field2, fieldN) VALUES (value1, value2, valueN)
Run Code Online (Sandbox Code Playgroud)
所以你的命令应该写成
SqlCommand command5 = new SqlCommand(@"INSERT INTO Questions
([Question Space], [Question Type]) VALUES
(@QuestionText, @checkedradiobutton)", connect);
Run Code Online (Sandbox Code Playgroud)
请注意参数占位符不应该用单引号括起来,因为这样做可以在文本文本中转换它们.("@QuestionText"在[Question Space]字段中插入字符串)
最后,尽量避免AddWithValue,它是一个有许多缺点的快捷方式,因为你可以阅读我们是否已经停止使用AddWithValue和数据访问代码如何影响数据库性能
这仍然是一行代码
command5.Parameters.Add("@QuestionText", SqlDbType.NVarChar).Value = QuestionText;
Run Code Online (Sandbox Code Playgroud)