CS0266:无法将类型'object'隐式转换为'System.Data.SqlClient.SqlDataReader'。这个错误导致行dr = cmd.executescalar() [英] CS0266: Cannot implicitly convert type 'object' to 'System.Data.SqlClient.SqlDataReader'. this error conduct the line dr=cmd.executescalar()
本文介绍了CS0266:无法将类型'object'隐式转换为'System.Data.SqlClient.SqlDataReader'。这个错误导致行dr = cmd.executescalar()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public int membercount(string tbl, string condition)
{
string query = null;
if (condition.Trim().Length > 0)
{
query = query + "where" + condition;
}
else
{
query = query;
}
cmd = new SqlCommand(query, con);
dr= cmd.ExecuteScalar();
return a;
}
推荐答案
正如我在代码块中看到的那样, dr是SqlDataReader 对象。 cmd.ExecuteScalar() [ ^ ]返回第一个查询返回的结果集中第一行的列。其他列或行将被忽略。
此外,我还可以看到代码中还有一个问题,即您的SQL查询错误。我在这里修改查询。您可以查看一次。
试试这个:
As I can see in your code block, dr is SqlDataReader object. Where as cmd.ExecuteScalar()[^] returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Additionally, I can see one more problem in your code is, your SQL query is wrong. I am modifying the query here. You can check it once.
Try this:
public int membercount(string tbl, string condition)
{
string query = "SELECT COUNT(*) FROM " + tbl; //Since your function is for counting member.
if (condition.Trim().Length > 0)
{
query = query + " where " + condition;
}
cmd = new SqlCommand(query, con);
int a = Convert.ToInt32(cmd.ExecuteScalar());//Converting the returned value to Int32
return a;
}
实际上Executescaler()方法返回
查询返回的结果集中第一行的第一列。额外的列或行将被忽略。
但你已将其分配给博士。这就是为什么你会收到这个错误。
Actually the Executescaler() method returns
the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
but u have assigned it to the dr .Thats why u are getting this error.
这篇关于CS0266:无法将类型'object'隐式转换为'System.Data.SqlClient.SqlDataReader'。这个错误导致行dr = cmd.executescalar()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文