mysql数据库在java中查询异常

IDEA使用sql语句查询异常
#这个sql 语句 是获取表的模糊查询 数据总数,在mysql数据库中查出来是5
/ select count(*) from t_student s1,t_clazz c1,t_group t1,t_city c2,t_mark t2 where s1.s_clazz_id=c1.id and t1.g_clazz_id=c1.id and c2.id=s1.s_city_id and t2.m_id=s1.s_mark_id and s1.name like concat('张','%') /
================================================================================

/***

 /***
     * 模糊查询总数
     * @param field    要查询的字段名
     * @param obscure  模糊字段
     * @return
     */
    @Override
    public int count(String field, String obscure) {
        String sql = "select count(*) from t_student s1,t_clazz c1,t_group t1,t_city c2,t_mark t2 where s1.s_clazz_id=c1.id and t1.g_clazz_id=c1.id and c2.id=s1.s_city_id and t2.m_id=s1.s_mark_id and ? like concat(?,'%')";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, field);
            ps.setString(2, obscure);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return rs.getInt("count(*)");
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return 0;
    }

//测试类

public class Text {
public static void main(String[] args) {
StudentDaoImpl studentDao = new StudentDaoImpl();
int count = studentDao.count("s1.name", "张");
**//_测试类里面测出来是怎么0啊**
System.out.println(count);
}
}

问题:为什么在数据库中查到的正确的5,在测试类里面查到的确是0?

【以下回答由 GPT 生成】

我怀疑问题出在SQL语句中使用了占位符代替字段名的部分,导致查询条件无法正确匹配。我会尝试修改代码中的SQL语句,同时加入相关的调试输出语句来验证和定位问题。

以下是修改后的代码和SQL语句:

/**
 * 模糊查询总数
 * @param field 要查询的字段名
 * @param obscure 模糊字段
 * @return
 */
@Override
public int count(String field, String obscure) {
    String sql = "select count(*) from t_student s1, t_clazz c1, t_group t1, t_city c2, t_mark t2 where s1.s_clazz_id=c1.id and t1.g_clazz_id=c1.id and c2.id=s1.s_city_id and t2.m_id=s1.s_mark_id and " + field + " like concat(?,'%')";
    try {
        System.out.println("生成的SQL语句:" + sql); // 添加调试输出
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, obscure);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            return rs.getInt("count(*)");
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return 0;
}

// 测试类
public class Test {
    public static void main(String[] args) {
        StudentDaoImpl studentDao = new StudentDaoImpl();
        int count = studentDao.count("s1.name", "张");
        System.out.println(count);
    }
}

您可以尝试运行这段代码,然后查看生成的SQL语句是否正确,以及是否得到了正确的结果。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^