-1

我不断收到读者错误。我只想能够从阅读器返回单个值。谁能帮帮我吗?

        DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");

        DbConnection conn = factory.CreateConnection();

        conn.ConnectionString = ConfigurationManager.ConnectionStrings["CompanyConnection"].ConnectionString;

        DbCommand comm = conn.CreateCommand();
        comm.CommandText = "getStockPrice";
        comm.CommandType = CommandType.StoredProcedure;

        DbParameter param = comm.CreateParameter();
        param.ParameterName = "@company";
        param.Value = CompanyName;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);
        conn.Open();

        DbDataReader reader = comm.ExecuteReader();
        string stock = reader;
        reader.Close();
        conn.Close();
        return Convert.ToDouble(stock);

这是存储过程:

        @company varchar(50)
    AS
Select stockPrice From Company_t
where companyName = @company;
4

4 回答 4

3

您必须执行以下操作:

string stock = reader.GetString(0);

或者

string stock = reader.GetString(reader.GetOrdinal("stockPrice"));

代替

string stock = reader;

编辑:

您可以使用GetDouble()而不是GetString()跳过Convert.ToDouble()

于 2013-02-28T22:40:50.960 回答
1

试着打电话ExecuteScalar

string stock = (string)comm.ExecuteScalar();
于 2013-02-28T22:41:49.773 回答
0

我认为您的代码在这里中断

string stock = reader;

你不能这样做,你必须实际从阅读器那里获取数据。

查看文档以获取更多信息

于 2013-02-28T22:38:24.050 回答
0

DataReader如果不读取数据,您将无法直接访问其中的数据。即使您的查询没有返回数据,此方法也不会破坏您的代码。

DbDataReader reader = comm.ExecuteReader();
string stock = "0";

while (reader.Read())
{
    // get the results of each column
    stock = reader["stockprice"].ToString();
    break;
}
reader.Close();
conn.Close();
return Convert.ToDouble(stock);
于 2013-02-28T22:51:13.460 回答