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

目前,我对尝试将答案保存/插入数据库中的表时的当前语法错误问题的含义感到困惑。当我尝试使用硬编码的变量时,它运行良好,但现在不是这种情况。


错误消息的一部分:


附加信息:')'附近的语法不正确


不知道我在做什么错。以下是我正在使用的代码以及错误所指向的位置。感谢您提供的任何帮助和说明。


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.";

    }


守着星空守着你
浏览 189回答 3
3回答

白衣染霜花

错误在这一行strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", " + strAnswer + ")";根据您的SQL查询和数据库,该字段Answer是类型varchar或的字段nvarchar。此类型的字段始终采用字符串类型的值。这已经由您完成了。但是SQL Server数据库在单引号内接受这些值''。因此,您的解决方案是strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";因为我strAnswer在的末尾添加了单引号strAnswer

侃侃尔雅

我同意有关字符串串联的评论。如果必须在代码中编写SQL查询,则应使用用户字符串插值。如果必须这样做,我会这样写:String strSQL = $"INSERT INTO Answer  (StudentID, QuestionID, Answer) VALUES ( {int32StudentID}, {int32QuestionID}, '{strAnswer}')";就是说,这不是为什么您会出现语法错误。您在字符串变量周围缺少单引号。试试这个:strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";
打开App,查看更多内容
随时随地看视频慕课网APP