C#处理SQL查询的最佳方法

时间:2017-12-12 05:24:34

标签: c# sql .net-4.5

我想用一个函数读取数据库记录,并将结果作为数组传递给另一个函数。我怎么能用.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;
         } 
     }
 }

我应该为result变量使用哪种数据类型以及如何更正内部组织数据?

遵循stackoverflow的规则我将此文本添加到我的问题中,因为它说问题主要包含代码。

4 个答案:

答案 0 :(得分:2)

你可以从sql将值存储到datatable然后你可以使用linq将datatable转换为arrey这里是代码

 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;
           }

答案 1 :(得分:0)

您应构造DTO(数据传输对象)以传递应用程序周围的值。

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

答案 2 :(得分:0)

以下是我的方法的代码块,我将如何提取数据并将其解析为数组。

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;
                }

    }

通话示例:

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

答案 3 :(得分:0)

我认为最好的解决方案:

    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;
     }