检查数据是否存在,然后更新,如果不存在,然后将其插入数据库 [英] Check data if exists then update if not exists then insert it to database

查看:449
本文介绍了检查数据是否存在,然后更新,如果不存在,然后将其插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友,

如果数据库中有可用数据,则更新该数据(如果不存在),然后将数据插入数据库中.但是,这应该在不使用任何存储过程的情况下实现.我需要使用c锋利的语言.


谢谢

Dear friends,

If the data is available in the database then update that data ,if not present then insert the data in the database.But here this should be achieved without using any stored procedure.Using c sharp language i need it.


Thanks

推荐答案

您可以通过几种方法执行此操作.例如,您可以首先尝试更新数据,如果没有更新,则将其插入.

另外,您可以先尝试获取数据,然后再进行插入/更新决策.

一种方法是使用表适配器,首先将数据获取到数据集(或数据表),然后进行修改.之后,您可以调用数据适配器更新以将更改反映到数据库.

另外,根据情况,您可能会发现MERGE Transact sql语句很有用.
You can do this several ways. For example you can first try to update the data and if no rows are updated insert it.

Also you can first try to fetch the data and then make the decision insert/update.

One way is to use table adapter, get the data first to a dataset (or datatable), then make modifications. After that you can call the data adapters update to reflect the changes to the database.

Also, depending on the situation, you may find MERGE transact sql statement useful.


创建与数据库的连接.
创建一个命令:从MyTable的SELECT id WHERE id = idOfRecordToHandle
运行命令:如果行数为零,则需要插入
插入:
创建一个新命令:INSERT INTO MyTable ...
要更新:
创建一个新命令:UPDATE MyTable SET ...
将适当的参数值添加到所需的任何命令.
运行命令.

实际的代码取决于您所使用的数据库,但是基本知识就在那里.
Create a connection to the database.
Create a command: SELECT id FROM MyTable WHERE id=idOfRecordToHandle
Run the command: if the number of rows is zero, you need an insert
To Insert:
Create a new command: INSERT INTO MyTable...
To Update:
Create a new command: UPDATE MyTable SET...
Add the appropriate parameter values to whichever command you need.
Run the command.

The actual code depends on the database you are using, but the basics are all there.


那是什么问题?
检查 ^ ]
So what is the problem?
Check insert and update data in database using C#[^]


这篇关于检查数据是否存在,然后更新,如果不存在,然后将其插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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