简体   繁体   English

从C#获取sql数据的最佳方法是什么?

[英]What is best approach to get sql data from C#

I'm trying to find optimal (fast vs easiest) way to access SQL Server code thru code in C#. 我试图通过C#中的代码找到最佳(快速和最简单)方式来访问SQL Server代码。

As I was learning from books I've encountered multiple suggestions usually telling me to do it via drag and drop. 当我从书本中学习时,我遇到了多个建议,通常告诉我通过拖放来做。 However since I wanted to do it in code first approach was to get data by column numbers, but any reordering in SQL Query (like adding/removing columns) was pain for me to fix. 但是,由于我想在代码中做到第一种方法是按列号获取数据,但SQL查询中的任何重新排序(如添加/删除列)都让我难以修复。

For example (don't laugh, some code is like 2 years old), I even coded special function to pass sqlQueryResult and check if it's null or not): 例如(不要笑,一些代码就像2岁),我甚至编写了特殊的函数来传递sqlQueryResult并检查它是否为null):

public static void exampleByColumnNumber(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = Locale.checkForNullReturnString(sqlQueryResult, 0);
            string var2 = Locale.checkForNullReturnString(sqlQueryResult, 1);
            }
            sqlQueryResult.Close();
        }
    }

Later on I found out it's possible thru column names (which seems easier to read with multiple columns and a lot of changing order etc): 后来我发现它可能通过列名称(这似乎更容易阅读多列和大量更改顺序等):

    public static void exampleByColumnNames(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = (string) sqlQueryResult["SomeColumn"];
            string var2 = (string) sqlQueryResult["SomeColumn2"];
            }
            sqlQueryResult.Close();
        }
    }

And 3rd example is by doing it by column names but using .ToString() to make sure it's not null value, or by doing If/else on the null check. 第三个例子是通过列名来实现的,但是使用.ToString()来确保它不是空值,或者通过在null检查上执行If / else。

    public static void exampleByColumnNamesAgain(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2], [SomeColumn3]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = (string) sqlQueryResult["SomeColumn"].ToString();
            DateTime var2;
        DateTime.TryParse(sqlQueryResult["SomeColumn2"].ToString());

        int varInt = ((int) sqlQueryResult["SomeColumn3"] == null ? 0 : (int) sqlQueryResult["SomeColumn3"];

            }
            sqlQueryResult.Close();
        }
    }

Please bare in mind that I've just created this for sake of this example and there might be some typos or some slight syntax error, but the main question is which approach is best, which is the worst (I know first one is the one that I dislike the most). 请记住,我刚刚为此示例创建了这个,并且可能存在一些拼写错误或一些轻微的语法错误,但主要问题是哪种方法最好,哪种方法最差(我知道第一种方法是一种)我最不喜欢的。

I will soon have to start / rewriting some portion of my little 90k lines app which has at least those 3 examples used widely, so i would like to get best method for speed and preferably easiest to maintain (hopefully it will be same approach). 我将很快开始/重写我的小90k行应用程序的一部分,至少有3个广泛使用的例子,所以我想获得最好的速度方法,最好是最容易维护(希望它将是相同的方法)。

Probably there are some better options out there so please share? 可能有一些更好的选择那么请分享?

It seems you may be looking at old books. 看来你可能正在看旧书。 If you're going to do it the "old fashioned way", then you should at least use using blocks. 如果你打算做的“老式的方式”,那么你至少应该使用using块。 Summary: 摘要:

using (var connection = new SqlConnection(connectionString))
{
    using (var command = new SqlCommand(commandString, connection))
    {
        using (var reader = command.ExecuteReader())
        {
             // Use the reader
        }
    }
}

Better still, look into Entity Framework . 更好的是,查看实体框架

Links: Data Developer Center 链接: 数据开发人员中心

If it's easy you're looking for, you can't do any better than Linq-to-SQL:- 如果您正在寻找它很容易 ,那么您不能做得比Linq-to-SQL更好: -

http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

If your SQL database already exists, you can be up-and-running in seconds. 如果您的SQL数据库已经存在,您可以在几秒钟内启动并运行。

Otherwise, I agree with John. 否则,我同意约翰。

you should have a look into these tutorials, 你应该看看这些教程,

[ http://www.asp.net/learn/data-access/][1] [ http://www.asp.net/learn/data-access/][1]

All the work you are planning is already been done. 您计划的所有工作都已完成。

have a look at this way of doing same what you are doinng 看看这种做同样事情的方式

  string preparedCommand =
  @"SELECT TOP 1 [SomeColumn],[SomeColumn2], [SomeColumn3]    
  FROM [Database].[dbo].[Table]
  WHERE [SomeOtherColumn] = @varValue";
  [1]: http://www.asp.net/learn/data-access/

More better way of doing the same above is by Using LINQ TO SQL 更好的方法是使用LINQ TO SQL

var result = from someObject in SomeTable
             where SomeColumnHasValue == ValueToCompare
             select new { SomeColumn, SomeColumn1, SomeColumn2};
  • No Type Safety Issues 没有类型安全问题
  • Visualise Database in C# while you work on it 在您使用C#时可视化数据库
  • at compile time less errors 在编译时减少错误
  • less code 更少的代码
  • more productive 更有成效

Following are some of the great resources for LINQ if you are interested 如果您有兴趣,以下是LINQ的一些重要资源

Hope it helps 希望能帮助到你

If you're looking into using just straight ADO.net you might want to go out and find Microsoft's Enterprise Library's Data Access Application Block . 如果您正在考虑直接使用ADO.net,您可能想要找出Microsoft的企业库的数据访问应用程序块。 David Hayden has a decent article that goes into some detail about using it. David Hayden有一篇很好的文章 ,详细介绍了如何使用它。

Good luck and hope this helps some. 祝你好运,希望这有助于一些人。

The easiest way to do data access in C#, to my mind, is using typed DataSets. 在我看来,在C#中进行数据访问的最简单方法是使用类型化的DataSet。 A lot of it really is drag-and-drop, and it's even easier in .NET 2.0+ than in .NET 1.0/1.1. 其中很多都是拖放式的,在.NET 2.0+中比在.NET 1.0 / 1.1中更容易。

Have a look at this article, which talks about using typed DataSets and TableAdapters: 看看这篇文章,其中讨论了使用类型化DataSet和TableAdapter:

Building a DAL using Strongly Typed TableAdapters and DataTables in VS 2005 and ASP.NET 2.0 在VS 2005和ASP.NET 2.0中使用强类型TableAdapter和DataTable构建DAL

A typed DataSet is basically a container for your data. 类型化DataSet基本上是数据的容器。 You use a TableAdapter to fill it (which happens with SQL or stored procs, whichever you prefer) and to update the data afterwards. 您使用TableAdapter来填充它(使用SQL或存储过程发生,无论您喜欢哪种)并随后更新数据。 The column names in each DataTables in your DataSet are autogenerated from the SQL used to fill them; DataSet中每个DataTable中的列名都是从用于填充它们的SQL中自动生成的; and relations between database tables are mirrored by relations between DataTables in the DataSet. 数据库表之间的关系通过DataSet中的DataTables之间的关系进行镜像。

Don't convert data to strings only to try to parse it; 不要仅将数据转换为字符串以尝试解析它; DataReaders have methods to convert SQL data to .Net data types: DataReaders有将SQL数据转换为.Net数据类型的方法:

using (var connection = new SqlConnection(Locale.sqlDataConnection))
using (var command = new SqlCommand(preparedCommand, connection))
using (var reader = command.ExecuteReader())
{
    int stringColumnOrdinal = reader.GetOrdinal("SomeColumn");
    int dateColumnOrdinal = reader.GetOrdinal("SomeColumn2");
    int nullableIntColumnOrdinal = reader.GetOrdinal("SomeColumn3");
    while (reader.Read())
    {
        string var1 = reader.GetString(stringColumnOrdinal);
        DateTime var2 = reader.GetDateTime(dateColumnOrdinal);
        int? var3 = reader.IsDBNull(nullableIntColumnOrdinal) ? null : (int?)reader.GetInt32(nullableIntColumnOrdinal);
    }
}

I test the many different ways for get data from sql server database and i faced & found fastest way is following: 我测试了从sql server数据库获取数据的许多不同方法,我遇到并发现最快的方法如下:

First of all create class with "IDataRecord" parameterized method as per your required properties. 首先根据您所需的属性使用“IDataRecord”参数化方法创建类。

       class emp
        {
            public int empid { get; set; }
            public string name { get; set; }
            public static emp create(IDataRecord record)
            {
                return new emp
                {
                    empid = Convert.ToInt32(record["Pk_HotelId"]),
                    name = record["HotelName"].ToString()
                };
            }
        }

Now create method for get data as below: 现在创建获取数据的方法如下:

public List<S> GetData<S>(string query, Func<IDataRecord, S> selector)
        {
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = query;
                cmd.Connection.Open();
                using (var r = cmd.ExecuteReader())
                {
                    var items = new List<S>();
                    while (r.Read())
                        items.Add(selector(r));
                    return items;
                }
            }
        }

And then call function like: 然后调用函数如:

var data = GetData<emp>("select * from employeeMaster", emp.create);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM