C# 如何在子查询中插入基于子查询的值
我有一个需要从windows窗体更新的表,我可以将显示的值更新到表中,因为我无法更新特定列,其中要更新的值必须是windows窗体上显示数据的参考值。参考值在另一个表中。代码如下:C# 如何在子查询中插入基于子查询的值,c#,mysql,.net,winforms,C#,Mysql,.net,Winforms,我有一个需要从windows窗体更新的表,我可以将显示的值更新到表中,因为我无法更新特定列,其中要更新的值必须是windows窗体上显示数据的参考值。参考值在另一个表中。代码如下: command.CommandText = "INSERT INTO tblComplaints (ComplaintID, Description,ComplaintTypeID,ReceivedDate,ComplaintTypeID)VALUES('" + TextBox7.Text + "','" + Tex
command.CommandText = "INSERT INTO tblComplaints (ComplaintID, Description,ComplaintTypeID,ReceivedDate,ComplaintTypeID)VALUES('" + TextBox7.Text + "','" + TextBox10.Text + "','" + dateTimePicker1.Text + "',???)";
代码中的问号(???)就是我所需要的。
更准确地说,ComplaintTypeName显示在ComboBox 1中的表单中,而我要求更新其ID,其值出现在TBLCompaintType中,假设您事先以某种方式指定了ComboBox值
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
comboBox1.Items.Add(item);
您可以执行以下操作:
command.CommandText = "INSERT INTO tblComplaints " +
"(ComplaintID, Description, ComplaintTypeID, ReceivedDate, ComplaintTypeID) " +
"VALUES (@Description,@ComplaintTypeID,@ReceivedDate,@ComplaintTypeID)";
command.Parameters.AddWithValue("@Description", TextBox7.Text);
command.Parameters.AddWithValue("@ComplaintTypeID", TextBox10.Text);
command.Parameters.AddWithValue("@ReceivedDate", dateTimePicker1.Text);
command.Parameters.AddWithValue("@ComplaintTypeID", comboBox1.SelectedValue);
注意,我从sql命令中删除了ComplaintID
。由于这是一条INSERT语句,您可能会得到该记录的生成ID。如果情况并非如此,则必须在命令中提供另一个参数
此外,您应该始终参数化命令,而不是通过字符串连接来构建命令,以防止sql注入。您不应该在这样的查询中直接使用文本框的文本值-如果文本包含单引号字符,则文本的其余部分将解释为sql而不是数据,为诚实的用户破坏应用程序,并允许恶意用户删除所有数据。不,我不希望添加combobox值。我需要添加其各自的ID。例如:我的第二个表有点像它有以下两列[ID,Name],现在我的表单显示Name,我希望ID插入我的TBLComplaint
值
通常表示它的ID,Text
包含文本表示,我使用可视研究中的combobox任务选项将combobox 1值iSeries化。不,当涉及到complainttypeid时,您上面传递的内容是不正确的,因为combobox中将显示complainttype,我需要的是表tblcomplainttype中的complainttype的complainttypeid,它将被传递到complaints表中。