【发布时间】:2020-04-27 14:06:27
【问题描述】:
// Find controls for on edit.
DropDownList ddlLocation = (DropDownList)(sender as ListView).EditItem.FindControl("ddlLocation");
TextBox txtQuestion = (TextBox)(sender as ListView).EditItem.FindControl("txtQuestion");
Label lblLocationID = (Label)(sender as ListView).EditItem.FindControl("lblLocationID");
// Set strSQL to empty string.
String strSQL = "";
// Develop SQL call.
strSQL = "";
strSQL += "UPDATE Question ";
strSQL += "SET LocationID = '" + ddlLocation.SelectedValue + "', Question = '" + txtQuestion.Text + "' ";
strSQL += " WHERE LocationID = " + lblLocationID.Text ;
// Define the network connection to the SQL Server database.
SqlConnection objSqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["2020LJCDT"].ConnectionString);
// Set up the SQL command object
SqlCommand objSqlCommand = new SqlCommand();
objSqlCommand.Connection = objSqlConnection;
objSqlCommand.CommandType = CommandType.Text;
objSqlCommand.CommandText = strSQL;
// Define the input parameters
objSqlCommand.Parameters.AddWithValue("@LocationID", ddlLocation.SelectedValue);
objSqlCommand.Parameters.AddWithValue("@Question", txtQuestion.Text);
// Open the connection
objSqlConnection.Open();
// Execute sql. Get number of rows affected.
numberOfRecords = objSqlCommand.ExecuteNonQuery();
// Close the data reader and the connection.
objSqlConnection.Close();
我的更新命令无法正常工作。由于某种原因,更新LocationID 会出现问题。我可以毫无问题地更新Question,只是不能更新LocationID。我在下拉列表中选择LocationID,它正确传递了值,但不会更新数据库。有没有人看到有什么不对?
这是我的数据库表的截图:
这些是被传递的值:
UPDATE Question
SET LocationID = '2086', Question = 'Test123'
WHERE LocationID = 2087
【问题讨论】:
-
删除
'2086'周围的单引号 - 并使用参数! -
您是否收到任何错误消息?一切看起来都不错,但是阅读后有几个 FYI:1)您不需要在 2086 左右使用单引号,因为 LocationID 是一个 INT(但我认为 SQL 会翻译它),2)您正在创建参数,但您不是使用它们。 LocationID 上是否有外键或约束?
-
@jefftrotman LocationID 是外键。
-
SQL Injection alert - 您应该不将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看Little Bobby Tables
-
@marc_s 我将全部更改为参数化查询。你还是有问题。 SQL 成功,但未更新 LocationID。 Question 属性是唯一正在更新的属性。
标签: c# asp.net sql-server