C# 从两个Sql表中选择并插入。C

C# 从两个Sql表中选择并插入。C,c#,C#,我的代码是有效的。请纠正我 示例我想说从*列中取2个值,其中。。。。 和列*中的2个值,其中 con.Open(); SqlCommand cmd = new SqlCommand ("INSERT INTO temp_rent(parts,size,color,quantities,barcode,name,mobile,code) select parts,size,color,quantities,barcode from inventory where barcode = ('" +

我的代码是有效的。请纠正我

示例我想说从*列中取2个值,其中。。。。 和列*中的2个值,其中

con.Open();
SqlCommand cmd = new SqlCommand
("INSERT INTO temp_rent(parts,size,color,quantities,barcode,name,mobile,code) select 
parts,size,color,quantities,barcode from inventory where barcode = ('" + textBox4.Text + "')
 select name,mobile,code from customermaster where code= '" + textBox1.Text + "')", con);
                    cmd.ExecuteNonQuery();
                    con.Close();
我的做法如下:

首先在visual studio 2015中,我添加了一个数据源。请考虑到不同版本的visual studio有不同的方法来添加数据源。因此,在VS2015中,单击

项目 添加新的数据源数据库 数据集 配置与数据库的连接 选择要使用的表 将数据集命名为mine is SO_testDataSet 完成后,项目中将有一个…DataSet.xsd。双击它

在这里,您将看到从数据库导入的表。右键单击临时租金的标题,因为您希望创建一个查询,该查询将在末尾插入临时租金

添加 查询 在这里,您可以使用SQL语句或创建新的存储过程。我建议使用第二种,但为了简单起见,现在就使用第一种。 插入 将以下内容粘贴到文本框中。如果愿意,请在查询生成器中选中它

INSERT INTO temp_rent
                 (parts, size, color, quantities, barcode, name, mobile, code)
SELECT        i.parts, i.size, i.color, i.quantities, i.barcode, cm.name, cm.mobile, cm.code
FROM            inventory AS i CROSS JOIN
                 customermaster AS cm
WHERE        (cm.code = @code) AND (i.barcode = @barcode)
将您的查询命名为我的是InsertQuery

完成,保存。在查询中,您可以看到交叉联接,因为inventory和CustomerMaster不是通过列联接的。这是一个简单的笛卡尔积。您还可以使用FROM inventory、customermaster或FROM inventory JOIN customermaster,因为ON是可选的。我们还可以看到@code和@barcode是参数化查询的占位符

在代码中,您可以使用添加的查询,如下所示:

SO_testDataSetTableAdapters.temp_rentTableAdapter adapter = new SO_testDataSetTableAdapters.temp_rentTableAdapter();
// I assume that code and barcode are the type of int in the database.
adapter.InsertQuery(int.Parse(textBox1.Text), int.Parse(textBox4.Text));

如果文本框包含一些有害字符串,int.Parse将引发异常,因为有害字符串不能被解析为int以防止sql注入。

首先,您不应该使用查询文本连接,因为它会导致sql注入和可能的值转义问题。改用参数化查询。我想让它变得更小、更简单——首先将其格式化,使其更具可读性。仅此一点就大大简化了代码。问题是什么?您可以编写一个存储过程并调用它,而不是这样…您希望在查询中得到什么结果?无法通过简单地阅读代码来理解它。。。这对读者来说也不是很友好。谷歌sql加入2。使用参数化查询。您拥有的是一种简单的sql注入方法。