【发布时间】:2018-04-25 19:42:41
【问题描述】:
在尝试将答案保存/插入到我的数据库中的表中时,我目前对我当前的语法错误问题的确切含义感到困惑。当我尝试使用硬编码变量进行此操作时效果很好,但现在情况并非如此。
部分错误信息:
附加信息:')' 附近的语法不正确
不知道我做错了什么。下面是我正在使用的代码和错误指向的位置。感谢您提供任何可能的帮助和澄清。
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.";
}
【问题讨论】:
-
这就是为什么你应该使用参数而不是连接。
-
多年来,这一直不是构建查询的正确方法。五分钟的研究会让你得到几篇数千个解释这一点的帖子和关于参数的信息。
-
我学院大部分CS课程的教授基本上都是教我们,然后强迫我们这样写。否则,我们会因为不遵循他的榜样而失分。
-
可能你的教授也需要看看 Stack Overflow 上的一些帖子。
标签: c# sql-server ado.net