我正在做一个小应用程序,用户输入一个查询块然后执行它们。
问题是我想要显示相关信息,例如,如果他输入的内容如下:
SELECT * FROM server;
UPDATE server SET name = 'Kojak';
得到:
我的打印循环如下:
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查询时,如何解决这个问题并能够获得受影响的行数?
感谢。
答案 0 :(得分:1)
您无法使用cmd.ExecuteReader()
执行非查询。您需要使用ExecuteNonQuery()
。
我想你需要解析SQL语句列表以确定它是什么类型的comamnd(例如SELECT
或UPDATE
),并调用适当的方法。
答案 1 :(得分:0)
@David:我是这样做的:
public int Execute(String block, dbStudio.components.DbsTab host)
{
this.Connect();
DbCommand cmd = this.dbConnection.CreateCommand();
DbDataReader reader = null;
cmd.CommandText = block;
int ret = -1;
try
{
long ticks = DateTime.Now.Ticks;
reader = cmd.ExecuteReader();
do
{
while (reader.Read())
{
String str = "";
for (int i = 0; i < reader.FieldCount; i++)
{
//host.WriteLine("Field " + i + ": " + reader[i].ToString());
str = str + reader[i].ToString() + " ";
}
host.WriteLine(str);
}
} while (reader.NextResult());
host.WriteLine("Block executed successfuly");
host.WriteLine(reader.RecordsAffected.ToString() + " Affected rows.");
host.WriteLine(((DateTime.Now.Ticks - ticks) / 1000).ToString() + "ms");
ret = reader.RecordsAffected;
}
catch (Exception e)
{
host.WriteLine(e.Message);
}
finally
{
this.Disconnect();
}
return ret;
}