c# - 插入带有 where 子句的语句 c#

标签 c# sql asp.net

我正在尝试根据 cookie 的值将详细信息插入表中,.这是代码

   SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
        conn.Open();
        string insertQuery = "insert into Details (Employees, Performance, TotalPerformance, Attitude, TotalAttitude) values(@employees, @performance ,@totalPerformance, attitude, totalAttitude)";
        SqlCommand com = new SqlCommand(insertQuery, conn);
        com.Parameters.AddWithValue("@employees", Request.QueryString["employees"]);
        com.Parameters.AddWithValue("@performance", totalPer.ToString());
        com.Parameters.AddWithValue("@totalPerformance", totalPercent.ToString());
        com.Parameters.AddWithValue("@attitude", totalAtt.ToString());
        com.Parameters.AddWithValue("@totalattitude", totalPercent.ToString());



        com.ExecuteNonQuery();

这很好用,但在字符串插入查询行中,我想添加一个 where 子句,如果该行中“name”列的值与 cookie 匹配,它将把值插入到特定行中。我不知道正确的语法 感谢您的帮助

最佳答案

你需要一个 UPDATE语句,而不是 INSERT 语句,因为您要修改现有记录。

using (
    SqlConnection conn =
        new SqlConnection(
            ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString))
{
    conn.Open();
    string updateQuery =
        @"UPDATE Details 
        SET Employees = @employeee, 
        Performance = @performance , 
        TotalPerformance = @totalPerformance,
        Attitude = @attitude,
        TotalAttitude = @totalattitude
        WHERE yourField = @yourConditionValue";

    using (SqlCommand com = new SqlCommand(updateQuery, conn))
    {
        com.Parameters.AddWithValue("@employees", Request.QueryString["employees"]);
        com.Parameters.AddWithValue("@performance", totalPer.ToString());
        com.Parameters.AddWithValue("@totalPerformance", totalPercent.ToString());
        com.Parameters.AddWithValue("@attitude", totalAtt.ToString());
        com.Parameters.AddWithValue("@totalattitude", totalPercent.ToString());
        com.Parameters.AddWithValue("@yourConditionValue", yourValue);
        com.ExecuteNonQuery();
    }
}

+1,用于在您的问题中使用参数,另一件事,enclose your Command and Connection object in using 语句。

关于c# - 插入带有 where 子句的语句 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25666920/

相关文章:

c# - ASP NET API - 使用 Azure AD SAML 协议(protocol)对用户进行身份验证,无需打开 Microsoft 登录页面

c# - 防止 ToolStripMenuItems 跳转到第二个屏幕

c# - 为什么这个 int 数组会抛出 IndexOutOfRangeException?

c# - 在图像中查找图像 C#

mysql - 无法使 SQL 查询正常工作

mysql - SQL ORDER BY 性能

asp.net - Bootstrap 多分辨率所有布局内联媒体查询 CSS 用于响应式设计,包括 Android iPhone 和 Web asp.net

java - SQL 结果集处理

asp.net - 如何在 ASP.NET 中获取网络打印机

asp.net - 错误: “A field or property with the name was not found on the selected data source” get only on server