c# - 将变量插入表中时出现语法错误 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.";
}
解决方案
首先,您不应该像这样构建 SQL 语句,它很容易出现很多问题,但是您的问题在于您的字符串,您的字符串周围没有单引号:
strSQL += " ( " + int32StudentID + ", " + int32QuestionID + ", '" + strAnswer + "')";
需要像我上面一样在 strAnswer 周围添加单引号
使用此处列出的参数: https ://msdn.microsoft.com/library/bb738521(v=vs.100).aspx
推荐阅读
- java - 使用 PKCS#11 令牌从 Java 程序内部连接到 sshd 服务器
- c# - VSTO ReportItem.Body 出现乱码
- regex - PRXMATCH 不适用于 SAS 中的 PRXPARSE 函数
- node.js - json 输入意外结束。文件无法完全解析
- android - 如何设置TextInputLayout的boxBackground不同颜色?
- python - SOQL python中的通配符
- c# - 反应式扩展 Observerable.FromAsync:如何等待异步操作完成
- node.js - 有没有办法在nodejs中将输入字段与pdf文档或图像一起上传并做出反应?任何解释相同的资源将不胜感激
- cassandra - Cassandra 是在更新记录时仅存储受影响的列还是在每次更新时存储所有列?
- php - 如何在PHP中用小数分隔字符串和数字