在 SQL table 中搜索字符串未成功

Search for string in SQL table unsuccessful

我正在尝试在 sql table 中搜索特定字符串,并 return 找到的观察结果数。但是,无论字符串是否在 table 中,它都会保持 returning -1。这是我的代码:

@{
    Layout = "~/_Layout.cshtml";
    Page.title = "TestArea";


    var db = Database.Open("Cafeen");
    string SearchWord = "Jolly";

    var msg = db.Execute("SELECT COUNT(*) FROM Products WHERE ProductName = @SearchWord");

}

<p>@msg</p>    

我是否应该使用 COUNT(*) 以外的东西? -1有什么意义?如果找不到字符串,我会假定表达式为 return 0

db.ExecuteSqlCommand.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 like SELECT, the return value is -1. If a rollback occurs, the return value is also -1.

查看以下链接可能会有帮助:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx

与 SQL 数据库相关的是:

SqlCommand.ExecuteScalar Method ()

(回复:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx

否则,参考Database.QueryValue方法(回复:https://msdn.microsoft.com/en-us/library/webmatrix.data.database.queryvalue(v=vs.111).aspx

两种方法return第一列/第一行的标量值。

此外,您可以使用 COUNT(1) 代替 SQL 语句中的 COUNT(*) 以获得更好的性能。

希望这可能有所帮助。

您正在使用 WebMatrix.Data 命名空间。在这种情况下,您应该调用 QuerySingle 方法而不是 Execute 方法,因为正如许多人已经指出的那样,该方法用于不返回行数据。

The Execute method is used to perform non-query commands on a database, such as the SQL Drop, Create, Delete, Update, and Insert commands.

此外,我建议将您的查询语句更改为性能更高的语句

var db = Database.Open("Cafeen");
string SearchWord = "Jolly";
string cmdText = @"IF EXISTS(SELECT 1 FROM Products 
                             WHERE ProductName = @searchWord)
                      SELECT 1 ELSE SELECT 0";
int exists = Convert.ToInt32(db.QuerySingle(cmdText, SearchWord));
.....