在C#中进行比较并插入数据库

编程入门 行业动态 更新时间:2024-10-26 10:32:02
本文介绍了在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#中进行比较并插入数据库

本文发布于:2023-10-20 22:25:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1512319.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据库

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!