Skip to main content
 首页 » 编程设计

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

2024年02月06日10EasonJim

我正在尝试根据 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 语句。