在C#中进行比较并插入数据库 [英] Comparisons in C# and inserting to database

查看:83
本文介绍了在C#中进行比较并插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



我正在尝试将值(X)插入数据库,但现在我要比较一下,

如果X的最后一个值不等于X的当前值,则INSERT到数据库表。

我真的不知道它的语法是什么。谢谢

Hello,

I am trying to insert value (X) to a database, but now i want to compare that,
if X last value is not equal to X present value then INSERT to a database table.
I really dont know what will be its syntax. Thanks

推荐答案

使用SQL



Using SQL

Create proc asp_savetable
(@newValue varchar(10)
@id int)
as
BEGIN
   Declare @oldvalue varchar(10)
   Select @oldvalue =name from table1 where id=@id
   If @oldvalue<>@newvalue
      insert into table1 values (@id,@newvalue)
END





这里Id,名字是我的表格中的两列1



使用c#





here Id,name are two columns in my table table1

Using c#

  using (SqlConnection conn = new SqlConnection(connString))
    {
		string oldvalue="";
		SqlCommand cmd=new SqlCommand("Select name from employee where id=@id",conn)
		cmd.Parameters.Add("@id", SqlDbType.Int);
		cmd.Parameters["@id"].Value = empid;
        	try
        	{
            		conn.Open();
            		oldvalue= cmd.ExecuteScalar().ToString();
        	}
       		 catch (Exception ex)
       		 {
            		Console.WriteLine(ex.Message);
        	}
	}

If (oldvalue!=newvalue)
{
	  using (SqlConnection conn = new SqlConnection(connString))
    {
		string oldvalue="";
		SqlCommand cmd=new SqlCommand("insert into employee values(@id,@name)",conn)
		cmd.Parameters.Add("@id", SqlDbType.Int);
		cmd.Parameters["@id"].Value = empid;
		cmd.Parameters.Add("@name", SqlDbType.VarChar);
		cmd.Parameters["@name"].Value = newvalue;
        	try
        	{
            		conn.Open();
            		cmd.NonExecuteQuery();
        	}
       		 catch (Exception ex)
       		 {
            		Console.WriteLine(ex.Message);
        	}
	}	
}


你的评论听起来就像你是一个新手一样 - 所以如果这样请嘲笑我不是这样的:



在您的C#代码中,您可能有一些代码可以执行以下操作



It sounds by your comments like you are a novice - so please fogive me if this isn''t the case:

In your C# code you probably have some code that does the following

Get X From COM port

Write X to database table





所以,你需要一个字段来存储X的旧值。



So, you need a field in your class to store the ''old'' value of X.

private int oldX = -1;





我用-1初始化它假设无法从COM端口接收-1 ...



现在您的代码可以更改为...





I initialise it with -1 on teh assumption that it is not possible to receive -1 from the COM port...

Now your code can change to...

Get X from COM PORT

if (X != oldX)
{
    oldX = X;
    write X to database table
}


这篇关于在C#中进行比较并插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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