Problem getting data from database

I am trying to get data from a database using the code below .....

if there is no data in the table, it will always be this statement

I use a mysql.net connector to receive data, and I make winforms applications using 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); } 

and the code below is for sqlexceution return function ...

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

even if there is no data, the process flow will flow to this line

table = ds.Tables [0];

how can i reduce this .....

will anyone help with this ....

+6
source share
3 answers

In your case, if you think that the catch block will be consumed if there is no row available, why are you mistaken, because even if there is no data after the query request is exucuted without exception, it creates a datatable with columns, but without a row.

for this, I think you can use the ds.table[0].rows.count , which returns 0 if there is no row in the datatable.

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

It returns an empty table. This is the usual behavior. If you want to have a null column, you should check the number of rows:

 If ( ds.Tables[0].Rows.Count >. 0 ) table = ds.Tables[0]; Else table=0 
+3
source

I'm not quite sure what you are asking here ... I assume you want it to skip the line table = ds.tables [0] if there is no data?

if this is the case where try / catch does not work as it does not throw an exception ... try something like this ...

 if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count >0) { table = ds.Tables[0]; } else { table = null; } 
+3
source

Source: https://habr.com/ru/post/897224/


All Articles