更新数据库中的记录中的各个字段时的最佳实践字段、数据库中

2023-09-03 23:22:38 作者:善良没用,你得漂亮

我创建使用.NET数据访问层。无处不在,我更新的数据库记录,我都用过SQL沿行

I have created a Data Access Layer using .NET. Everywhere that I update a database record, I have used sql along the lines of

更新客户SET姓=:名字,姓氏=:名字,地址1 =:地址1,地址= 1:地址,...等

UPDATE Customer SET FirstName=:FirstName, LastName=:LastName, Address1=:Address1, Address2=:Address2,....etc

这意味着,在记录每个字段被更新,即使只有一个字段可能已被改变。一位同事采取了问题,这一点,他说,如果它已经改变了我们应该只更新一个字段,理由是带宽的问题 - 说我们有160字段,然后我们通过数据的160场。我想我可以节省Web服务器和数据库服务器之间的带宽,如果我查了值是否发生了变化,并产生上实际上改变的值完全基于SQL。

This means that every field in the record is updated, even though only one field may have been changed. A colleague has taken issue with this, saying that we should only update a field if it has changed, citing bandwidth as the issue - say we had 160 fields, then we pass the data for 160 fields. I guess I could save bandwidth between the web server and the database server if I checked whether a value had changed, and generated sql based purely on the values that were actually changed.

Web服务器和客户端之间,我现在需要通过新旧价值观,所以可能我增加带宽有(但ASP.NET已经做了这个无论如何,我不知道我们可以切换该位关闭,因此这可能不是一个问题)。

Between the web server and the client, I now need to pass both old and new values, so potentially I increase bandwidth there (but then ASP.NET does this already anyway, and I'm not sure we can switch that bit off so that's probably not an issue).

那么,什么是最好的做法?我应该担心更新数据库中记录的所有字段?我怎么会去只更新已更改的领域?

So what is best practise? Should I be worried about updating all fields in a database record? How would I go about updating only the fields that have changed?

修改补充10月29日:有谁知道NHibernate的呢?也许这是投资时间学习如何这样做的一个参数。

Edit added 29 October: Does anyone know what NHibernate does? Perhaps this is an argument to invest time learning how to do it that way.

推荐答案

premature的优化是一切罪恶的根源。

Premature optimization is the root of all evil.

有没有理由为这个,你实际上有一个带宽的问题?

Is there justification for this, do you actually have a bandwidth problem?

在我的经验,跟踪变化可能是大量的工作(即大量的code保持),取决于它是如何实现的。有一些优雅的方式,但我认为你在做什么是好的,除非有证据支持的变化。

In my experience, tracking changes can be lots of work (ie lots of code to maintain) depending on how it is implemented. There are some elegant ways but I think what you are doing is fine unless there is some evidence to support a change.

如果您正在计划执行的更改跟踪我肯定不会聊天与它的数据库中的一些自定义窗体。让你的对象的副本,在本地当你第一次从数据库中把它和比较反对的。

If you were planning to implement some custom form of change tracking I would certainly not 'chat' with the database about it. Make a copy of your object locally when you first pull it from the DB and compare against that.