C# Insert And Select 在一个字符串查询中

C# Insert And Select in one string query

我使用 select 查询来读取值,然后使用下面的代码通过一些更新重新插入(不更新)它们。 我正在尝试 运行 此查询同时插入和 select 但没有工作,我没有出现任何错误。

string docdetls = "Insert into DocDetls (DocStatus,  DocType, DocNo,SeqNo,ItemCode,Quantity,Price,Disc,DiscAmount,VAT,ExpDate)"+
                    "(SELECT 2 as DocStatus,  DocType, @newdocno as DocNo,SeqNo,ItemCode,Quantity,Price,Disc,DiscAmount,VAT,ExpDate FROM docdetls where  DocStatus=@stat and DocNo=@docno)";
MySqlCommand cmd4 = new MySqlCommand(docdetls, con);
cmd4.Parameters.AddWithValue("stat", "1");
cmd4.Parameters.AddWithValue("newdocno", DocNoTxtBox.Text);
cmd4.Parameters.AddWithValue("DocNo",no );
con.Open();
cmd4.ExecuteNonQuery();
con.Close();

如果我 运行 在 mysql workbench 上使用某些值进行相同的查询。 这可能吗?我怎样才能做到这一点?

回答后更新

       string docdetls = "Insert into DocDetls (DocStatus,  DocType, DocNo,SeqNo,ItemCode,Quantity,Price,Disc,DiscAmount,VAT,ExpDate)"+
                        "(SELECT 2 as DocStatus,  DocType, @newdocno as DocNo,SeqNo,ItemCode,Quantity,Price,Disc,DiscAmount,VAT,ExpDate FROM docdetls where  DocStatus=@stat and DocNo=@docno)";
                    MySqlCommand cmd4 = new MySqlCommand(docdetls, con);
                    cmd4.Parameters.AddWithValue("stat", "1");
                    //cmd4.Parameters.AddWithValue("newdocno", DocNoTxtBox.Text);
                    cmd4.Parameters.AddWithValue("DocNo",no );
                    cmd4.Parameters.Add("@newdocno", MySqlDbType.Int16).Value = DocNoTxtBox.Text;
                    con.Open();
 cmd4.ExecuteNonQuery();
                    con.Close();

还是不行..

我看到了一些东西;

您不能参数化您的列名。您只能参数化您的值。这就是 @newdocno as DocNo 不应该工作的原因。如果您想将此列作为输入,那么在将它连接到您的字符串中或使用白名单之前,您确实需要进行一些强有力的验证。

为了更清楚,您应该在命令中定义您的参数名称并且您的参数集合相同。也就是说,如果你有

where  DocStatus=@stat and DocNo=@docno

在您的命令中,您的参数集合应为;

cmd4.Parameters.AddWithValue("@stat", "1");
cmd4.Parameters.AddWithValue("@DocNo",no );

作为最佳实践,不要使用 AddWithValue 方法。 It might generates unexpected and surprising results. Use .Add() method 指定您的参数类型及其大小。

并使用 using statement 自动处理您的数据库连接和命令,而不是手动调用 Close 方法。

我已经用下面的代码完成了

 string docdetls = "Insert into DocDetls (DocStatus,  DocType, DocNo,SeqNo,ItemCode,Quantity,Price,Disc,DiscAmount,VAT,ExpDate)"+
                        "(SELECT 2 as DocStatus,  DocType, @newdocno as DocNo,SeqNo,ItemCode,Quantity,Price,Disc,DiscAmount,VAT,ExpDate FROM docdetls where  DocStatus=@stat and DocNo=@docno)";
                    MySqlCommand cmd4 = new MySqlCommand(docdetls, con);
                    cmd4.Parameters.AddWithValue("stat", "1");
                    //cmd4.Parameters.AddWithValue("newdocno", DocNoTxtBox.Text);
                    cmd4.Parameters.AddWithValue("DocNo",no );
                    cmd4.Parameters.Add("@newdocno", MySqlDbType.Int16).Value = DocNoTxtBox.Text;
                    con.Open();
                    cmd4.ExecuteNonQuery();
                    con.Close();