Cannot implicitly convert type 'System.Data.Common.DbDat
本文关键字:System Data Common DbDat implicitly convert type Cannot | 更新日期: 2023-09-27 18:01:34
我一直得到一个错误的阅读器。我只希望能够从阅读器返回单个值。有人能帮帮我吗?
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;
您必须这样做:
string stock = reader.GetString(0);
或
string stock = reader.GetString(reader.GetOrdinal("stockPrice"));
不是string stock = reader;
编辑:您可以使用GetDouble()
代替GetString()
,并跳过Convert.ToDouble()
尝试呼叫ExecuteScalar
string stock = (string)comm.ExecuteScalar();
我觉得你的代码有问题
string stock = reader;
你不能那样做,你必须实际从读取器获取数据。
查看文档获取更多信息
您不能直接访问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);