You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Access数据库SQL查询返回空结果,请求排查解决

问题排查与解决方案

一、SQL语句逻辑问题(最可能的根源)

你的SQL语句存在两个关键隐患:

  1. 重复记录导致计数错误
    如果ItemInRecipe中同一个recipeId对应同一个itemId有多条重复记录,COUNT(itemId)会把重复项算进去,导致最终计数大于itemList.Count,无法匹配筛选条件。应改为COUNT(DISTINCT itemId)来统计不重复的物品数量。
  2. SQL注入风险与字符串拼接漏洞
    直接拼接itemName会导致如果物品名称包含单引号(比如Tom's Soup),SQL语句会直接报错,同时存在注入风险。

修改后的SQL逻辑(推荐用参数化查询):

public static List<int> GetTheRecipesIdsWithAllItems(List<string> itemList)
{
    List<int> recipeIdList = new List<int>();
    // 构建参数占位符,避免字符串拼接问题
    string itemPlaceholders = string.Join(",", Enumerable.Range(0, itemList.Count).Select(_ => "?"));
    string query = @"
        SELECT recipeId FROM ItemInRecipe 
        WHERE itemId IN (SELECT itemId FROM Item WHERE itemName IN ({0})) 
        GROUP BY recipeId 
        HAVING COUNT(DISTINCT itemId) = ?
    ";
    query = string.Format(query, itemPlaceholders);

    using (OleDbConnection conn = new OleDbConnection(YourConnectionString))
    {
        conn.Open();
        using (OleDbCommand cmd = new OleDbCommand(query, conn))
        {
            // 添加物品名称参数
            foreach (var item in itemList)
            {
                cmd.Parameters.AddWithValue($"@item", item);
            }
            // 添加物品数量参数
            cmd.Parameters.AddWithValue("@count", itemList.Count);

            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    recipeIdList.Add(reader.GetInt32(0));
                }
            }
        }
    }
    return recipeIdList;
}

二、Web服务与客户端调用排查

  1. 验证Web服务端返回值
    在Web方法中添加日志或调试代码,确认Dbf.GetTheRecipesIdsWithAllItems(itemList)是否真的返回了非空列表:
    [WebMethod]
    public List<int> GetTheRecipesIdsWithAllItems(List<string> itemList)
    {
        var result = Dbf.GetTheRecipesIdsWithAllItems(itemList);
        // 可以写入日志或调试输出result.Count
        return result;
    }
    
  2. 检查客户端传入的物品列表
    确认GetList()返回的l是否包含有效物品名称:
    • 检查是否有空字符串、不存在的物品名称
    • 验证物品名称在Item表中是否存在(大小写是否匹配,Access默认不区分大小写,但特殊字符可能有问题)
  3. 确认GetRecipesByIds方法逻辑
    如果recipeIdList为空,GetRecipesByIds自然返回空数组;如果recipeIdList有值但返回空,需要检查该方法的SQL是否正确关联Recipe表。

三、Session存储问题

  1. 确认Session启用状态
    确保页面的EnableSessionState属性为True(默认是启用的,但如果手动修改过可能关闭):
    <%@ Page Language="C#" EnableSessionState="True" %>
    
  2. 验证Session读写逻辑
    在存储Session后立即读取验证:
    Session["recipeswithitems"] = recipes;
    // 调试时添加以下代码
    var testRecipes = Session["recipeswithitems"] as Recipe[];
    // 查看testRecipes是否为空
    

内容的提问来源于stack exchange,提问作者KK2007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:33:18