微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 从数据库获取数据的问题

我试图通过使用下面的代码数据库获取数据…..

如果表中没有数据,它将始终进入
这个说法

我使用mysql.net连接器获取数据,我正在做winforms应用程序
使用c#

public DataTable sales(DateTime startdate,DateTime enddate)
     {
         const string sql = @"SELECT memberAccTran_Source as Category,sum(memberAccTran_Value) as Value
                              FROM memberacctrans
                              WHERE memberAccTran_DateTime BETWEEN @startdate AND @enddate
                              GROUP BY memberAccTran_Source";

         return sqlexecution(startdate,enddate,sql);
     }

以下代码用于返回sqlexceution …函数..

private static DataTable sqlexecution(DateTime startdate,DateTime enddate,string sql)
 {
         var table = new DataTable();
         using (var conn = new MysqL.Data.MysqLClient.MysqLConnection(connectionstring))
         {
             conn.open();

             var cmd = new MysqL.Data.MysqLClient.MysqLCommand(sql,conn);

             var ds = new DataSet();

             var parameter = new MysqL.Data.MysqLClient.MysqLParameter("@startdate",MysqL.Data.MysqLClient.MysqLDbType.DateTime);
             parameter.Direction = ParameterDirection.Input;
             parameter.Value = startdate.ToString(dateformat);
             cmd.Parameters.Add(parameter);

             var parameter2 = new MysqL.Data.MysqLClient.MysqLParameter("@enddate",MysqL.Data.MysqLClient.MysqLDbType.DateTime);
             parameter2.Direction = ParameterDirection.Input;
             parameter2.Value = enddate.ToString(dateformat);
             cmd.Parameters.Add(parameter2);

             var da = new MysqL.Data.MysqLClient.MysqLDataAdapter(cmd);

             da.Fill(ds);
             try
             {
                 table = ds.Tables[0];

             }
             catch
             {
                 table = null;
             }
         }
         return table;
     }

即使没有数据,流程也会流向此行

table = ds.Tables[0];

我怎么能减少这个……

任何人都会对此有所帮助….

解决方法

在你的情况下,如果你认为如果没有可用的行,那么catch块会被释放,因为即使没有数据,一旦选择查询被排除而没有例外,它会创建带有列但没有行的数据表.

为此,我认为你可以使用ds.table [0] .rows.count属性,如果datatable中没有行,则返回0.

if ( ds.Tables[0].Rows.Count > 0 )
     table = ds.Tables[0];
else
     table=null;

原文地址:https://www.jb51.cc/csharp/92255.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐