简体   繁体   中英

C# best way to handle SQL query

I want to read database records with one function and pass result as array to another function. How can I do it with .NET4.5?

namespace test
{
    class Program
    {
        static void Main()
        {
            ... data = GetData();
            string result = HandleData(data);
        }

        private static string HandleData(... data)
        {
            return string result
        }

        private static ... GetData()
        {
            ... result = new ...;
            SqlDataReader reader;
            using (SqlConnection conn = new SqlConnection(conf))
            {
                 string query = "SELECT [ID], [Desc], [tID] FROM [table] WHERE [Updated] = 0";
                 try
                 {
                     conn.Open();
                     SqlCommand cmd = new SqlCommand();
                     cmd.CommandText = query;
                     cmd.Connection = conn;
                     reader = cmd.ExecuteReader();

                     if(reader.HasRows)
                     {
                          while (reader.Read())
                          {
                               result.Add(reader[0], reader[1], reader[2]);
                          }
                     }
                     reader.Close();

                 }
                 catch(Exception e)
                 {
                 }
                 finnaly
                 {
                     conn.Close();
                     conn.Dispose();
                 }
             }
             return result;
         } 
     }
 }

Wich datatype should I use for result variable and how to correct organize data inside?

Followed on stackoverflow's rules I'm adding this text to my question, because it says that is question contains mostly code.

you can store value to datatable from sql and then you can convert datatable to arrey by using linq here is code

 Private static ... GetData()
           {
             try
                {
                  var dt = new DataTable();
                  var cmd = new SqlCommand();
                  cmd.CommandText = @"SELECT name,address FROM [table_name] WHERE id = @id";
                  cmd.Parameters.AddwithValue("@id",id);
                  var da = new SqlDataAdapter(cmd);
                  da.Fill(dt);
                }
             catch (Exception ex)
                {

                }
             finally
                {
                  if (cmd.Connection.State == ConnectionState.Open)
                   {
                     cmd.Connection.Close();
                   }
                }

               var stringArr = dt.Rows[0].ItemArray.Select(x => x.ToString()).ToArray();
               return stringArr;
           }

The best solution in my opinion:

    private static DataTable GetData()
    {
        DataTable result = new DataTable();
        using (SqlConnection conn = new SqlConnection(conf))
        {
             string query = "SELECT [ID], [Desc], [tID] FROM [table] WHERE [Updated] = 0";
             try
             {
                 conn.Open();
                 SqlCommand cmd = new SqlCommand();
                 cmd.CommandText = query;
                 cmd.Connection = conn;
                 SqlDataAdapter da = new SqlDataAdapter(cmd);
                 da.Fill(result);
                 da.Dispose();
             }
             catch(Exception e)
             {
             }
             finnaly
             {
                 conn.Close();
                 conn.Dispose();
             }
         }
         return result;
     } 

You should construct DTO (data transfer object) to pass the value around the application.

    private static void Main(string[] args)
    {
        var dt = new DataTable();

        var col = new DataColumn { DataType = typeof(int), ColumnName = "ID" }; dt.Columns.Add(col);
        col = new DataColumn { DataType = typeof(string), ColumnName = "Desc" }; dt.Columns.Add(col);
        col = new DataColumn { DataType = typeof(int), ColumnName = "tID" }; dt.Columns.Add(col);

        var row = dt.NewRow();
        {
            row["ID"] = 1;
            row["Desc"] = "This is description";
            row["tID"] = 2;
        }
        dt.Rows.Add(row);

        var dto = ToDTO<UpdatedDto>(dt);

    }

    private static List<object> ToDTO<T>(DataTable dt)
    {

        var reult = (from rw in dt.AsEnumerable()
                     select new UpdatedDto
                     {
                         ID = Convert.ToInt32(rw["ID"]),
                         Desc = Convert.ToString(rw["Desc"]),
                         tID = Convert.ToInt32(rw["tID"])
                     }).ToList();
        return reult.ConvertAll<object>(o => (object)o);
    }

Here is chunk of code of my method on how i pull out the data and parse it to array.

public int find_data_on_id(string id, out string[] strTxnid)
  {
      cmd.Parameters.Clear();
      cmd.CommandText = @"SELECT name,address FROM [table_name] WHERE id = @id";
      cmd.Parameters.AddwithValue("@id",id);

      strTxnid = new string[5];

                try
                {
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();
                    strTxnid[0] = dr["id"].ToString();
                    strTxnid[1] = dr["name"].ToString();
                    strTxnid[2] = dr["address"].ToString();
                    dr.Close();
                    return 0;
                }
                catch (Exception ex)
                {
                    console.writeline("db internal error");
                    return -1;
                }

    }

Call Example :

public void example_call()
  {
       string[] info;
       int Respond = find_data_on_id(1,out info );
       string name = info[1];
       string address = info[2];
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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