为什么 com.ExecuteNonQuery() return -1 总是。在所有情况下

why com.ExecuteNonQuery() return -1 Always . in all cases

com.ExecuteNonQuery() 总是 returns -1 - 在所有情况下。

为什么总是 = -1?

SqlConnection conn = newSqlConnection(ConfigurationManager.ConnectionStrings["UsersConnectionString"].ConnectionString);

conn.Open();

string insertquery = " select UserName from Users where Username='" + CurrentName + "' ";

SqlCommand com = new SqlCommand(insertquery, conn);
com.ExecuteNonQuery();

int ii = com.ExecuteNonQuery();

Response.Write(ii);

这是因为您将它与 SELECT SQL 命令一起使用。

来自 SqlCommand.ExecuteNonQuery 的文档(强调我的):

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

不清楚您要实现的目标,但这基本上不是实现目标的方法。

您正在使用 select 查询,因此结果将始终为 -1。

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1.

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["UsersConnectionString"].ConnectionString);
conn.Open();
string query = "select UserName from Users where lower(Username)=lower('" + CurrentName + "')";
SqlCommand com = new SqlCommand(query, conn);
string result = "";
result = com.ExecuteScalar() == null ? "" : com.ExecuteScalar().ToString();
conn.Close();
Response.Write(result);

试试这个