2016-07-25 138 views
0
 string ProductType = comboBoxProductType.Text; 
     string ProductID = "Select ProductID from Productinformation where Name = '" + ProductType + "'"; 
     string query = "Insert into CustStoreProd (ProductID) VALUES (?ProductID)"; 
     MySqlCommand cmd = new MySqlCommand(query, mySQLconnection); 
     cmd.Parameters.AddWithValue("?ProductID", "ProductID"); 
     cmd.ExecuteNonQuery(); 

我想插入从选择查询“产品ID”的值插入值,我测试串ProductID作品,如果我只是插入一个cmd.Parameters.AddWithValue("?ProductID", "1");,它也能工作,但是当我把productID纳入parameters.addwithvalue,它不起作用。它只是整个项目的一个功能,所以我创建了外部的mysql数据库连接。SELECT查询

+2

您可以只使用INSERT INTO ... SELECT。但是你应该参数化你的'WHERE'子句以避免SQL注入。 –

回答

0

你在哪里运行查询ProductID。您没有运行查询ProductID来获取ProductId并在随后的查询中使用它。

首先运行ProductID查询以从表中获取产品ID,然后在插入查询中使用产品ID。请参阅以下示例代码。

string ProductType = comboBoxProductType.Text; 
     string ProductID = "Select ProductID from Productinformation where Name = '" + ProductType + "'"; 
     string query = "Insert into CustStoreProd (ProductID) VALUES (?ProductID)"; 
     MySqlCommand cmd = new MySqlCommand(ProductID, mySQLconnection); 
int pid = Convert.ToInt32(cmd.ExecuteScalar()); //assuming product id is integer 
     cmd.CommandText = query; 
     cmd.Parameters.AddWithValue("?ProductID", pid); 
     cmd.ExecuteNonQuery(); 
+0

非常感谢 –

0

修改下面一行从

cmd.Parameters.AddWithValue("?ProductID", "ProductID");

cmd.Parameters.AddWithValue("?ProductID", ProductID); //Remove "" around productID 
+0

我尝试过,但仍然努力工作。我尝试将其更改为(“?ProductID”,ProductType);如果producttype的值为1,则它可以正常工作,但是当我更改回作为选择查询的productID时,它不起作用 –

+0

调试?您收到的产品ID号是什么? –

+0

@StevenHuang您是否尝试用'@'替换'?'? –

0

试试这样说:

string ProductType = comboBoxProductType.Text; 
     string ProductID = "Select ProductID from Productinformation where Name = '" + ProductType + "'"; 
     string query = "Insert into CustStoreProd (ProductID) VALUES (@ProductID)"; 
     MySqlCommand cmd = new MySqlCommand(query, mySQLconnection); 
     cmd.Parameters.AddWithValue("@ProductID", "ProductID"); 
     cmd.ExecuteNonQuery(); 

变化的价值?以@希望它有帮助。 或者您的ProductID可能是一个自动增量主键,无法完成。

+0

否它不起作用:( –

+0

是您的productid是主键或不? –