开发者

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#.

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.

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

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] = @va开发者_JAVA技巧rValue";
        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.

    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).

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. 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:-

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.

Otherwise, I agree with John.


you should have a look into these tutorials,

[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

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
  • at compile time less errors
  • less code
  • more productive

Following are some of the great resources for LINQ if you are interested

  • http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
  • http://www.hookedonlinq.com/MainPage.ashx
  • https://stackoverflow.com/questions/47740/what-are-some-good-linq-resouces

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 . David Hayden has a decent article that goes into some detail about using it.

Good luck and hope this helps some.


The easiest way to do data access in C#, to my mind, is using typed DataSets. 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.

Have a look at this article, which talks about using typed DataSets and TableAdapters:

Building a DAL using Strongly Typed TableAdapters and DataTables in VS 2005 and ASP.NET 2.0

A typed DataSet is basically a container for your data. You use a TableAdapter to fill it (which happens with SQL or stored procs, whichever you prefer) and to update the data afterwards. The column names in each DataTables in your DataSet are autogenerated from the SQL used to fill them; and relations between database tables are mirrored by relations between DataTables in the DataSet.


Don't convert data to strings only to try to parse it; DataReaders have methods to convert SQL data to .Net data types:

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:

First of all create class with "IDataRecord" parameterized method as per your required properties.

       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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜