首页 > 解决方案 > 将变量插入表中时出现语法错误 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.";
    }

标签: c#sql-serverado.net

解决方案


首先,您不应该像这样构建 SQL 语句,它很容易出现很多问题,但是您的问题在于您的字符串,您的字符串周围没有单引号:

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

需要像我上面一样在 strAnswer 周围添加单引号

使用此处列出的参数: https ://msdn.microsoft.com/library/bb738521(v=vs.100).aspx


推荐阅读