使用IF条件将值添加到数据库表 [英] Adding values to a database table with IF condition

查看:79
本文介绍了使用IF条件将值添加到数据库表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Table_1中添加了 hexvalue 。但如果hexvalue不是AA(或任何指定值),那么我需要将该十六进制值插入Table_2。我该怎么做 ?谢谢

I am adding hexvalue in Table_1 . But if the hexvalue is not AA (or any specified value) then, i need to insert that hexvalue to Table_2. How can i do it ? Thanks

try
{
   SqlConnection sqlconn = new SqlConnection("Data Source=AAN-PC;Initial Catalog=mon26;Integrated Security=True");
   SqlDataAdapter sa = new SqlDataAdapter();

   string query = "insert into Table_1(SensorValue,Time) values(@SV, @TM)";
   sa.InsertCommand = new SqlCommand(query, sqlconn);
   sa.InsertCommand.Parameters.AddWithValue("@SV", hexvalue);
   sa.InsertCommand.Parameters.AddWithValue("@TM", DateTime.Now.ToString());

   sqlconn.Open();
   try
   {
       sa.InsertCommand.ExecuteNonQuery();
    }
    catch (FormatException ex) { MessageBox.Show(ex.Message); }
                MessageBox.Show("Record Inserted");
               
    //  Update Datagridview
    mon26DataSet1.GetChanges();
    table_1TableAdapter.Fill(mon26DataSet1.Table_1);

    sqlconn.Close();
}





由Jibesh添加的预标签[/ Edit]

推荐答案

try
{
   SqlConnection sqlconn = new SqlConnection("Data Source=AAN-PC;Initial Catalog=mon26;Integrated Security=True");
   SqlDataAdapter sa = new SqlDataAdapter();

   string query;
   if(hexvalue =""AA")
    query = "insert into Table_1(SensorValue,Time) values(@SV, @TM)";
   else
    query = "insert into Table_2(SensorValue,Time) values(@SV, @TM)";

   sa.InsertCommand = new SqlCommand(query, sqlconn);
   sa.InsertCommand.Parameters.AddWithValue("@SV", hexvalue);
   sa.InsertCommand.Parameters.AddWithValue("@TM", DateTime.Now.ToString());

   sqlconn.Open();
   try
   {
       sa.InsertCommand.ExecuteNonQuery();
    }
    catch (FormatException ex) { MessageBox.Show(ex.Message); }
                MessageBox.Show("Record Inserted");
               
    //  Update Datagridview
    mon26DataSet1.GetChanges();
    table_1TableAdapter.Fill(mon26DataSet1.Table_1);

    sqlconn.Close();
}


这篇关于使用IF条件将值添加到数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆