在项目不可用时添加新数据

时间:2016-08-08 02:51:22

标签: c# visual-studio ms-access-2007

我是非常新的编程,我很难想到如何在数据库中不存在项目代码时添加新项目。它似乎运行顺利,直到我添加else语句。在这里我的代码:

private void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            con.Open();
            OleDbCommand command = new OleDbCommand(@"Select * from TblInventory where ItemCode=itemcode");
            command.Connection = con;
            command.Parameters.AddWithValue("@itemcode", txtItem.Text);

            OleDbDataReader reader = command.ExecuteReader();

            if (reader.HasRows == true)
            {
                OleDbCommand cmd = new OleDbCommand(@"Update TblInventory set Quantity = Quantity + @Quantity 
WHERE ItemCode = @itemcode");
                cmd.Connection = con;                   
                cmd.Parameters.AddWithValue("@Quantity",Convert.ToInt32(txtQuantity.Text));
                cmd.Parameters.AddWithValue("@itemcode", txtItem.Text);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Data Saved !");
            }
            else
            {
                OleDbCommand cmdInsert = new OleDbCommand(@"insert into TblInventory (ItemCode,ProductName,Quantity)
values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "')");
                cmdInsert.Connection = con;
                cmdInsert.ExecuteNonQuery();
                MessageBox.Show("New Data Added");
            }

            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error  " + ex);
        }
    }

2 个答案:

答案 0 :(得分:1)

在数据库中查找现有记录的最佳方法之一是计算给定记录标准的数量。

OleDbCommand command = new OleDbCommand(@"Select COUNT(ItemCode) from
                                          TblInventory where ItemCode= @itemcode");

然后使用ExecuteScalar()代替ExecuteReader()

Int32 count = (int32) command.ExecuteScalar();

ExecuteScalar()会返回查询结果第一行的第一列,即您itemCode的计数。您可以阅读此OneSignal以获取更多信息。

然后你可以做简单的条件逻辑。

if (count > 0) // means that itemCode has 1 or more record count found in the db.
{
     // Do the update logic here..
}
else
{
     // Do the insert logic here...
}

答案 1 :(得分:0)

我已经找到了答案。 从这里:

OleDbCommand command = new OleDbCommand(@"Select * from TblInventory where ItemCode=itemcode");   

对此:

 OleDbCommand command = new OleDbCommand(@"Select * from TblInventory where ItemCode='" + txtItem.Text + "'");