ADO.NET 动态执行多个查询
我正在做一个小应用程序,用户输入一组查询然后执行它们。
问题是我想显示相关信息,例如如果他输入类似以下内容:
SELECT * FROM server;
UPDATE server SET name = 'Kojak';
它得到:
- 选定的行
- 受 UPDATE 影响的行数
我的打印循环看起来像:
reader = cmd.ExecuteReader();
do
{
while (reader.Read())
{
if (!(reader.RecordsAffected > 0))
{
for (int i = 0; i < reader.FieldCount; i++)
host.WriteLine("Field " + i + ": " + reader[i].ToString());
}
else {
host.WriteLine(reader.RecordsAffected.ToString() + " Affected rows.");
}
}
} while (reader.NextResult());
host.WriteLine("Block executed successfuly");
问题是我无法设法区分 SELECT 和 UPDATE,因为 reader.Read() 在到达第二个查询时返回 FALSE。 当存在 UPDATE/DELETE/INSERT 查询时,如何解决这个问题并能够获取受影响的行数?
谢谢。
I'm doing a little app where a user enters a block of queries and then executes them.
The thing is that I want to show relevant information, like for example if he inputs something like:
SELECT * FROM server;
UPDATE server SET name = 'Kojak';
It gets:
- The rows selected
- The number of rows affected by the UPDATE
My printing loop looks like:
reader = cmd.ExecuteReader();
do
{
while (reader.Read())
{
if (!(reader.RecordsAffected > 0))
{
for (int i = 0; i < reader.FieldCount; i++)
host.WriteLine("Field " + i + ": " + reader[i].ToString());
}
else {
host.WriteLine(reader.RecordsAffected.ToString() + " Affected rows.");
}
}
} while (reader.NextResult());
host.WriteLine("Block executed successfuly");
The thing is that I can't manage to make the difference between SELECTs and UPDATEs, because reader.Read() returns FALSE when it reaches the second query.
How can I solve that and be able to get the number of affected rows when there's a UPDATE/DELETE/INSERT query ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用
cmd.ExecuteReader()
执行非查询。您需要使用ExecuteNonQuery()
。我想您需要解析 SQL 语句列表来确定它是什么类型的命令(例如
SELECT
或UPDATE
),并调用适当的方法。You can't use
cmd.ExecuteReader()
to execute non queries. You need to useExecuteNonQuery()
.I would imagine you will need to parse the list of SQL statements to determnine what sort of comamnd it is (e.g.
SELECT
orUPDATE
), and call the appropriate method.@David:我是这样做的:
@David: here's how I did it: