c# ExecuteNonQuery 总是返回零
我认为连接没有任何问题,因为当我打开它时,它不会抛出任何错误。所以我猜错误是在我执行命令时发生的。这是我的代码:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM cars", conn);
cmd.CommandType = CommandType.Text;
int numbers = cmd.ExecuteNonQuery();
我尝试使用消息框来显示 numbers
的值,但结果始终为 0。表 cars 包含 5 条记录。那么为什么我没有得到正确的结果呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为您正在执行查询,并且 ExecuteNonQuery 返回受影响的行数,当您选择时该行数始终为 0,因为您没有更改任何内容(即 INSERT、UPDATE 或 DELETE)
Because you are executing a query, and ExecuteNonQuery returns the number of rows effected, which when you select is always 0 since you aren't changing anything (ie. INSERT,UPDATE or DELETE)
ExecuteNonQuery
仅返回 UPDATE、DELETE 或 INSERT 操作影响的行数。对于 SELECT 语句中的行数,请尝试:ExecuteNonQuery
only returns the number of rows affected for UPDATE, DELETE or INSERT operations. For the number of rows in the SELECT statement, try:对于匿名投反对票的人来说,OP 的关键部分是:
OP显然试图获取表中的记录计数(标量聚合)而不是所有表数据。
我的回答:
这是因为您的查询返回的是表而不是标量值,并且您调用了不正确的函数。您的查询应该是:
并且 ExecuteNonQuery 实际上并不期望返回任何结果。 (您通常使用 ExecuteNonQuery 运行插入、更新和删除操作。)您应该使用 ExecuteScalar 需要单值结果,例如 count(*)。
现在大家在一起:
To the anonymous downvoter, the key part of the OP:
The OP is obviously trying to get a count of records in the table (a scalar aggregate) and not all of the table data.
My answer:
That's because your query is returning a table and not a scalar value and you're calling the incorrect function. Your query should be should be:
And ExecuteNonQuery doesn't actually expect any results to be returned. (You usually run insert, update and delete operations with ExecuteNonQuery.) You should be using ExecuteScalar which expects a single-valued result such as count(*).
All together now:
尝试使用 ExecuteScalar 应该可以给你计数。 ExecuteNonQuery 不会返回查询结果。您查看的返回值表明有多少行受到您的语句的影响,在您的情况下为零。
Try using ExecuteScalar that should give you the count. ExecuteNonQuery doesn't return the results from your query. The return your looking at indicates how many rows were affected by your statement, in your case zero.
ExecuteNonQuery 顾名思义,不进行查询。它通常用于插入或更新并返回受影响的记录数。对于您提供的查询,您应该使用 ExecuteReader 或 DataAdapter 及其 Fill 方法来填充数据表。
ExecuteNonQuery as the name tells you does not make a query. it is normally used for inserts or updates and returns the number of affected records. for the query you provided you should use ExecuteReader or a DataAdapter and its Fill method to fill a datatable.