尝试使用update命令更新SQL数据库

时间:2020-04-27 14:06:27

标签: c# asp.net sql-server

// 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,它正确传递了值,但不会更新数据库。有人看错吗?

这是我的数据库表的屏幕截图:

enter image description here

这些是要传递的值:

UPDATE Question 
SET LocationID = '2086', Question = 'Test123'  
WHERE LocationID = 2087

2 个答案:

答案 0 :(得分:0)

删除单引号'2086'并使用字符串中的参数:

const string strSQL = "UPDATE Question " +
    "SET LocationID = @LocationID, Question = @Question " +
    " WHERE LocationID = @OldLocationID";

// 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);
objSqlCommand.Parameters.AddWithValue("@OldLocationID", lblLocationID.Text);

答案 1 :(得分:0)

在此行上放置一个断点:

// Execute sql. Get number of rows affected. 
numberOfRecords = objSqlCommand.ExecuteNonQuery();

点击后,将objSqlCommand.CommandText的值复制并粘贴到SSMS中并在其中执行。您得到什么结果?

相关问题