在c#类或函数中获取sql结果

时间:2022-11-29 10:35:51

i am using the same sql query in many places.

我在很多地方使用相同的SQL查询。

I would like to put my sql query in a c# class or a function and then, call the function, How can i do this ? and how can i call this function later,

我想将我的sql查询放在c#类或函数中,然后调用函数,我该怎么做?以后如何调用此函数,

thanks.

my code:

con.Open();
    cmd = new SqlCommand("select top(1) Image_path from Images", con);
    dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        Image1.Src = dr["Image_path"].ToString();
        Image2.Src = dr["Image_path"].ToString();
    }
    con.Close();

1 个解决方案

#1


1  

public static List<ImageClass> GetImages()
{
   var objList = new List<ImageClass>();
   string connectionString = "yourConnection";

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        con.Open();

        using (var command = new SqlCommand("Select top(1) Image_path from Images", con))
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                 objList.Add(new ImageClass()
                                   {
                                      Src = reader["Image_path"].ToString()
                                   });
                 objList.Add(new ImageClass()
                                   {
                                      Src = reader["Image_path"].ToString()
                                   });
            } 
        }

    }
      return objList ;
}

When you need it

当你需要它

var imageList = GetImages();

#1


1  

public static List<ImageClass> GetImages()
{
   var objList = new List<ImageClass>();
   string connectionString = "yourConnection";

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        con.Open();

        using (var command = new SqlCommand("Select top(1) Image_path from Images", con))
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                 objList.Add(new ImageClass()
                                   {
                                      Src = reader["Image_path"].ToString()
                                   });
                 objList.Add(new ImageClass()
                                   {
                                      Src = reader["Image_path"].ToString()
                                   });
            } 
        }

    }
      return objList ;
}

When you need it

当你需要它

var imageList = GetImages();