简体   繁体   中英

How can i pass parameter to LIMIT ? Can i save all query output in one string?

I have 2 questions, kind of related:

1).How can i pass the value of a parameter to limit ? is it possible ?

i tried with this:

log.CommandText = "SELECT * from log order by date desc limit ?param1";  

but it doesnt work because the parameter is passed like: "2".

SOLVED with:

log.CommandText = String.Format("SELECT * from log order by date desc limit {0}, yourIntNumber) 

2). Can i save the output of the query above in one variable in C#? i tried something like this.. but logs does not contain everything..

                while (Reader.Read())
                {
                    for (int i = 0; i < Convert.ToInt16(lognr); i++)
                    {

                        logs = logs + (Reader.GetValue(i).ToString());  
                    }

                }

For your first qustion :-

You can use Top keyword eg :- For MSSQL (Microsoft SQL)

Select TOP 3 * From Table_name

For MYSQL

Select * From Table_name LIMIT 3

Above will return top 3 rows.

For your second question,

while (Reader.Read())
 {
      for (int i = 0; i < Convert.ToInt16(lognr); i++)
       {

        logs = logs + (Reader.GetValue(i).ToString());  
        }

   }
}

This code is checking the condition Convert.ToInt16(lognr) and that's why it is not returning everything.

Hope above information will help you :)

1).How can i pass the value of a parameter to limit ? is it possible ?

i tried with this:

log.CommandText = "SELECT * from log order by date desc limit ?param1";  

but it doesnt work because the parameter is passed like: "2".

SOLVED with:

log.CommandText = String.Format("SELECT * from log order by date desc limit {0}, yourIntNumber)

2). Can i save the output of the query above in one variable in C#? i tried something like this.. but logs does not contain everything..

        while (Reader.Read())
        {
            for (int i = 0; i < Convert.ToInt16(lognr); i++)
            {

                logs = logs + (Reader.GetValue(i).ToString());  
            }

        }

Solved:

log.CommandText = String.Format("SELECT * from log order by date desc limit {0}", lognr);  //the output has 3 columns and several rows.
Reader = log.ExecuteReader();
int i = 0;
while (Reader.Read())
{
logs = logs + "\r\n" + Reader.GetValue(0).ToString() + " " + Reader.GetValue(1).ToString() + " "+ " " + Reader.GetValue(2).ToString();
i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM