0

I have a method for adding values to the database for all operations.

If this is selected from the database and this select return more rows from the database, how can I get the rows and store in an array?

This is the method code :

public void ExcuteProcedure(string procName, List<SqlParameter> procparams)
{
            try
            {
                SqlConnection mycon = new SqlConnection(connectionString);
                mycon.Open();
                SqlCommand mycom = new SqlCommand();
                mycom.Connection = mycon;
                mycom.CommandText = procName;
                mycom.CommandType = CommandType.StoredProcedure;
                foreach (var item in procparams)
                {
                    SqlParameter myparm = new SqlParameter();
                    myparm.ParameterName = item.ParameterName;
                  //  myparm.SqlDbType = item.SqlDbType;
                    myparm.Value = item.Value;
                    mycom.Parameters.Add(myparm);
                }
              var n= mycom.ExecuteScalar();

                mycon.Close();
            }
            catch (SqlException e)
            {
                Console.WriteLine("Error Number is : " + e.Number);
                Console.WriteLine("Error Message is : " + e.Message);
            }
}
4

3 回答 3

7

You need to call mycom.ExecuteReader(), which will give you a SqlDataReader which can read through the results.

Call Read() to advance through the rows.

于 2013-01-18T17:00:40.720 回答
2

It never ceases to amaze me the number of times I see devs trying to abstract away simple database connectivity; and the myriad of ways they inevitably screw it up.

The following may sound mean, but it needs said: Clean up your code, it leaks like a sieve. Using clauses around the connection and command objects are pretty much mandatory. As it stands if you forget a single parameter or put in a bad value you will leak connections. Once the connection pool is filled up your app will crash in all sorts of interesting, and usually hard to debug, ways.

Next, if you aren't sure how to properly get records back from a database then you probably shouldn't try to abstract the code calling your procedures. Either use a lightweight ORM like Dapper or learn how what you are doing will ultimately involve a lot of extraneous code that the next developer on your project will want to rip out.

/rant over.

Getting back to the question: ExecuteScalar returns a single value. You need to use ExecuteReader. I'd suggest that you simply take the results of the reader, stuff it into a datatable and pass that back to the calling code.

于 2013-01-18T17:07:56.047 回答
0
var n = mycom.ExecuteScalar();

Scalar: an atomic quantity that can hold only one value at a time

  • Return a DataReader instead, and iterate through its rows
  • Fill a DataSet by using a DataAdapter (this is more appropriate if you have multiple tables in the result set).
于 2013-01-18T17:01:05.810 回答