Confused between SqlCommand & SqlDataAdapter

亡梦爱人 提交于 2019-12-03 06:24:26

Errorstacks summed it right:

  • SqlAdapter is used to fill a dataset.
  • SqlCommand can be used for any purpose you have in mind related to Create/Read/Update/Delete operations, stored procedure execution and much more.

In addition:

  • SqlCommand CAN have one big advantage against usage of raw strings in regards of security - they CAN protect you from Sql Injections. Just use parameters for values provided by the user instead of string.Format(...).

My personal preference is to wrap ANY sql strings in SqlCommand and add SqlParameters to it in order to avoid Sql Injection by malicious users.
Regarding performance of the two approaches - I don't expect that there is any difference. (If someone can prove me wrong - do it!).
So I would suggest to stick with the longer variant 1 and use commands plus parameters if necessary.

A bit of a side note - Datasets and DataTables are a bit out of game recently due to Linq2Sql and Entity Framework.
But of course the knowledge of plain old SqlCommands/Adapters/Readers is welcome :)

Hurry-up! Turn your attention to LINQ!!!

No more gran'ma stuff like SQLDataset or TableAdapters, no open connection. Everything gets smoother with LINQ.

LINQ sample:

dim result = from emp in myDataContext.Employees where emp.Salary > 10000 Select emp.ID, emp.SurName, ....

myDatagrid.datasource = result.toList

With LINQ, you don't have to worry about single quotes or crlf within your queries...

And you'll even have intellisense on the SQL tables, columns and objects!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!