SQL/C# - 执行查询的最佳方法
我需要从 ac# 类中执行 sql 查询。我想到了 2 个选项
- 启动 sqlcmd 进程。
- 使用 SqlCommand 对象。
我的问题是哪种方法更好?重要的是,该解决方案只能在短时间内保持与服务器的连接。
如果上述想法不好,我愿意接受其他想法。
提前致谢。
I need to execute a sql query from within a c# class. I have thought of 2 options
- Starting a process of sqlcmd.
- Using a SqlCommand object.
My question is which would be the better way? It's important that the solution only holds a connection to the server for a short time.
I'm open to other ideas if the above aren't good.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 SqlCommand。此代码只会在很短的时间内保持连接处于活动状态(只要您的查询是高性能的):
Use a SqlCommand. This code will only keep the connection alive for a very short period of time (as long as your query is performant):
来自 MSDN:
以下示例创建一个SqlConnection、SqlCommand 和 SqlDataReader。该示例读取数据,并将其写入控制台。最后,该示例在退出Using 代码块时关闭SqlDataReader,然后关闭SqlConnection。
From MSDN:
The following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. The example reads through the data, writing it to the console. Finally, the example closes the SqlDataReader and then the SqlConnection as it exits the Using code blocks.
这取决于。如果您不关心查询分叉使用 sqlcmd 的进程的结果可能没问题。另一方面,如果您需要控制结果,那么最好使用 ADO.NET。为了避免长时间保持连接打开状态,请确保禁用 ADO.NET 连接池,通过将
Pooling=false
添加到连接字符串中:It depends. If you don't care about the result of the query forking a process which uses sqlcmd might be OK. If on the other hand you need to control the results it would be better to use ADO.NET. To avoid keeping the connection open for a long time make sure you disable ADO.NET connection pooling by adding
Pooling=false
to your connection string:我认为 SqlCommand 是明显的赢家,因为您不需要连接不同的进程。完成后您可以立即关闭数据库连接。
然后,您还可以将应用程序分发到没有
sqlcmd
可用的计算机。I think SqlCommand is a clear winner because you don't need to wire up a different process. You can close the database connection as soon as you're done with it.
And then you can also distribute the application to machines that don't have
sqlcmd
available.我认为 SqlCommand 是个好主意,但请记住,此类仅在连接到 SQL Server 时可用。如果您正在处理 Oracle,或者与其他数据库的 OleDb 连接,则需要其他类型的命令/连接类。所有数据命令对象均继承自 DbCommand,所以我会阅读相关内容。
I think SqlCommand is a good idea, but keep in mind this class is only available when connecting to SQL Server. You'll need some other type of Command/Connection classes if you're dealing with Oracle, or an OleDb connection to some other database. All of the data command objects inherit from DbCommand, so I would read up on that.