SQL / C# - 用于执行查询的最佳方法 [英] SQL/C# - Best method for executing a query

查看:93
本文介绍了SQL / C# - 用于执行查询的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一个C#类中执行一个SQL查询。我想到了2个选项

I need to execute a sql query from within a c# class. I have thought of 2 options


  1. 启动SQLCMD的过程。

  2. 使用SqlCommand对象。

我的问题是,这将是更好的办法?重要的是,该解决方案仅持有很短的时间与服务器的连接。

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.

感谢。

推荐答案

使用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):

DataTable results = new DataTable();

using(SqlConnection conn = new SqlConnection(connString))
    using(SqlCommand command = new SqlCommand(query, conn))
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
           dataAdapter.Fill(results);

这篇关于SQL / C# - 用于执行查询的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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