为了账号安全,请及时绑定邮箱和手机立即绑定

将变量插入表中时出现语法错误Visual Studios 2015 C#

将变量插入表中时出现语法错误Visual Studios 2015 C#

C#
守着星空守着你 2021-04-29 10:11:20
目前,我对尝试将答案保存/插入数据库中的表时的当前语法错误问题的含义感到困惑。当我尝试使用硬编码的变量时,它运行良好,但现在不是这种情况。错误消息的一部分:附加信息:')'附近的语法不正确不知道我在做什么错。以下是我正在使用的代码以及错误所指向的位置。感谢您提供的任何帮助和说明。protected void btnSaveAnswers_Click(object sender, EventArgs e){        Int32 int32StudentID = Convert.ToInt32(Session["StudentID"]);        Int32 int32QuestionID = Convert.ToInt32(Session["QuestionID"]);        String strAnswer = "";        // Save the student's answer to the Answer table.        // Develop the SQL call.        String strSQL = "";        strSQL = "INSERT ";        strSQL += "INTO Answer ";        strSQL += " (StudentID, QuestionID, Answer) ";        strSQL += "VALUES ";        strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", " + strAnswer + ")";        // Define the network connection to the SQL Server database.        SqlConnection objSqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["OPT"].ConnectionString);        // Create the SQL command object.        SqlCommand objSqlCommand = new SqlCommand();        objSqlCommand.Connection = objSqlConnection;        objSqlCommand.CommandType = CommandType.Text;        objSqlCommand.CommandText = strSQL;        // Open the connection.        objSqlConnection.Open();        // Execute the Insert statement.        objSqlCommand.ExecuteNonQuery();        // Close the connection.        objSqlConnection.Close();        this.Master.MessageForeColor = System.Drawing.Color.White;        this.Master.Message = "You have saved your answer for this question, click next to continue.";    }
查看完整描述

3 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

错误在这一行

strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", " + strAnswer + ")";

根据您的SQL查询和数据库,该字段Answer是类型varchar或的字段nvarchar。此类型的字段始终采用字符串类型的值。这已经由您完成了。但是SQL Server数据库在单引号内接受这些值''。因此,您的解决方案是

strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";

因为我strAnswer在的末尾添加了单引号strAnswer


查看完整回答
反对 回复 2021-05-15
?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

我同意有关字符串串联的评论。如果必须在代码中编写SQL查询,则应使用用户字符串插值。

如果必须这样做,我会这样写:

String strSQL = $"INSERT INTO Answer  (StudentID, QuestionID, Answer) VALUES ( {int32StudentID}, {int32QuestionID}, '{strAnswer}')";

就是说,这不是为什么您会出现语法错误。您在字符串变量周围缺少单引号。试试这个:

strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";


查看完整回答
反对 回复 2021-05-15
  • 3 回答
  • 0 关注
  • 187 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信