如何从sql server数据库中检索数据并在c#中进行操作

本文关键字:操作 数据 检索 sql server 数据库 | 更新日期: 2023-09-27 18:29:49

我是asp.net的新手。我正在尝试从asp.net网站的SQL Server中检索数据。这是我在SQL、中的表的结果

Day_Of_Week    Product_Count
-----------------------------
Sunday              8
Monday            150
Tuesday            80
Wednesday          95
Thursday          345
Friday            229
Saturday           48

这是我在c#中的代码,

    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection(Settings.DatabaseConnectionString);
    SqlCommand com = new SqlCommand("Select * from tblProducts");
    com.CommandType = CommandType.Text;
    com.Connection = con;
    con.Open();
    SqlDataAdapter da = new SqlDataAdapter(com);
    da.Fill(dt); 
   int monday = Convert.ToInt32(dt.Rows[1]["Product_Count"]);
   int tuesday = monday + Convert.ToInt32(dt.Rows[2]["Product_Count"]);
   int wednesday = tuesday + Convert.ToInt32(dt.Rows[3]["Product_Count"]);
   int thursday = wednesday + Convert.ToInt32(dt.Rows[4]["Product_Count"]) ;
   int friday = thursday + Convert.ToInt32(dt.Rows[5]["Product_Count"]);

现在,如果周日没有记录,它就不会显示周日行,我必须更改c#代码。相反,我想放一个开关盒之类的东西,这样如果星期一,我就可以写dt了。Rows[0],如果当天是星期二,则为dt。行[0]等

让我知道这样做的最佳选择是什么。任何帮助都将不胜感激。

谢谢。

如何从sql server数据库中检索数据并在c#中进行操作

您需要重新考虑您的方法。既然你只想按天获取产品数量,我会这样做,而不是依赖行号。

public static int FetchProductCountByDayOfWeek(DayOfWeek dayOfWeek)
{
    using(SqlConnection con = new SqlConnection(Settings.DatabaseConnectionString))
    {
         con.Open();
         SqlCommand com = new SqlCommand("Select * from tblProducts where Day_Of_Week = @day_of_week");
         com.CommandType = CommandType.Text;
         com.Connection = con;
         com.Parameters.AddWithValue("@day_of_week", dayOfWeek.ToString());
         using (SqlDataAdapter da = new SqlDataAdapter(com))
         {
               DataTable dt = new DataTable();
               da.Fill(dt);
               return Convert.ToInt32(dt.Rows[0]["Product_Count"]);
         }
    }
}

然后你会这样称呼它:

int monday = ProductHelper.FetchProductCountByDayOfWeek(DayOfWeek.Monday);

尽管这不如一次读取行的效率高,因为它要执行多个DB调用。

您可以使用foreach来遍历行,并使用开关来设置数据。首先预先初始化变量。

int monday = 0;
int tuesday = 0;
// and repeat
foreach(DataRow row in dt.Rows)
{
    switch(row["Days_Of_Week"].ToString().ToLower())
    {
        case "monday":
             monday = (int)row["Product_Count"];
        break;
        case "tuesday":
             tuesday = (int)row["Product_Count"] + monday;
        break;
        // repeat for each
    }
}

最好使用查询检索所需的数据,这样您就不必在C#中操作它了。

您可以使用T-SQL语句来检测某一天何时没有行。这不是您想要的确切查询,但基本上您可以使用ISNULL来检测没有行的情况,例如没有计数的天数。

SELECT ISNULL(
(SELECT 1 FROM tblProducts T
WHERE T.Day_Of_Week = @DayName and T. Product_Count > 0), 0)

假设将查询更改为使用PIVOT SQL语句

string query = @"
   SELECT 'Day Production' As DayProduction, Sunday, Monday, Tuesday, Wednesday, 
                                             Thursday, Friday, Saturday
FROM (SELECT Day_Of_Week, ProductCount FROM tblProducts) as tbp
PIVOT
(
    SUM(ProductCount)
    FOR Day_Of_Week IN ( Sunday, Monday, Tuesday,Wednesday,Thursday,Friday,Saturday )
) AS Totals";

现在你的代码可以被重写为

using(SqlConnection con = new SqlConnection(Settings.DatabaseConnectionString))
using(SqlCommand cmd = new SqlCommand(query, con))
{
     con.Open();
     // The query will return just one row with eight columns
     using(SqlDataReader reader = cmd.ExecuteReader())
     {
       if(reader.Read())
       {  
         // The column at ordinal 0 is the DayProduction one....
         // Check if column at ordinal 1 (Sunday) contains a DBNull.Value or not...
         int sunday = reader.IsDBNull(1) ? 0 : Convert.ToInt32(reader[1]);
         int monday = reader.IsDBNull(2) ? 0 : Convert.ToInt32(reader[2]);
         int tuesday = reader.IsDBNull(3) ? 0 : Convert.ToInt32(reader[3]);
         int wednesday = reader.IsDBNull(4) ? 0 : Convert.ToInt32(reader[4]);
         int thursday = reader.IsDBNull(5) ? 0 : Convert.ToInt32(reader[5]);
         int friday = reader.IsDBNull(6) ? 0 : Convert.ToInt32(reader[6]);
         int saturday = reader.IsDBNull(7) ? 0 : Convert.ToInt32(reader[7]);
       }
     }
}

上一个查询的行被旋转为列,周日(或其他任何一天)如果不存在,则始终作为DBNull.Value.

返回