java - 使用 AND 和 Where 从网页传递空字符串以选择查询时遇到问题

标签 java mysql sql

我正在尝试使用选择查询根据来自网页的输入从我的 sql 数据库中获取值。我粘贴了查询和下面的代码。问题是查询需要为每个变量输入以获取数据,因为我使用的是 AND。如果我不输入某个值,它不会抛出任何输出。请告诉我如何从数据库中获取数据,即使某些变量为空字符串。

     String host = reqt.getParameter("hostname");
     String uuid = reqt.getParameter("cinum");
     String cdir = reqt.getParameter("custcode");
     String customer = reqt.getParameter("custname");
     String mgip = reqt.getParameter("mgmtip");
     String cusip = reqt.getParameter("custip");
     String bakip = reqt.getParameter("backip");
     String ismtick = reqt.getParameter("ismticket");
     String tickmean = reqt.getParameter("ticketmean");
     String mgtlev = reqt.getParameter("mgmtlvl");
     String ptchcat = reqt.getParameter("patchcat");
     String ptchsc = reqt.getParameter("patchsch");
     String vmsite = reqt.getParameter("site");
     String vmcep = reqt.getParameter("cep");
     String vmscope = reqt.getParameter("scope");
     String os = reqt.getParameter("platform");
      String plattype = reqt.getParameter("ostype");
   Statement stmt = null;
   Class.forName("com.mysql.jdbc.Driver");
   Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/CMS_SCS_PORTAL", "root", "test");
  String sql = "Select * from inventory_table where ISNULL(hostname) = '"+host+"' AND ISNULL(uuid) = '"+uuid+"' AND ISNULL(cdir) = '"+cdir+"' AND ISNULL(customer) = '"+customer+"' AND ISNULL(management_ip) = '"+mgip+"' AND ISNULL(customer_ip) = '"+cusip+"' AND ISNULL(backup_ip) = '"+bakip+"' AND ISNULL(ism_ticket_state) = '"+ismtick+"' AND ISNULL(ticket_state_meaning) ='"+tickmean+"' AND ISNULL(management_level) = '"+mgtlev+"' AND ISNULL(patch_category) = '"+ptchcat+"' AND ISNULL(patch_schedule) = '"+ptchsc+"' AND ISNULL(host_site) = '"+vmsite+"' AND ISNULL(VM_Cep) = '"+vmcep+"' AND ISNULL(VM_Scope) = '"+vmscope+"' AND ISNULL(Operating_System) = '"+os+"' AND ISNULL(Operating_System_Type) = '"+plattype+"' LIMIT 10000";

stmt = conn.createStatement(); 结果集 rs = stmt.executeQuery(sql);

最佳答案

这里有三个提示:

  1. 使用prepareStatement、占位符和绑定(bind)参数。
  2. 我认为你的意思是 COALESCE(fieldname, '') 而不是 ISNULL(fieldname)
  3. 密切关注数据类型。我不确定 MySQL 如何将字符串作为 boolean 值处理,因为它们实际上并没有真正的 native boolean 类型(我认为 iirc 内部使用整数)。

第一步是模拟您的查询并在您的 rdbms 中的命令行中尝试它,并确保它执行您希望它执行的操作。先解决这个问题。然后使用 prepareStatement 和绑定(bind)参数重写。

不清楚这个查询在您的代码示例中应该做什么,所以很遗憾,这可能是我们能做的最好的事情。

关于java - 使用 AND 和 Where 从网页传递空字符串以选择查询时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41760051/

相关文章:

java - 如何在 Calendar 对象中将 String 转换为 dd MMM yyyy 格式

c# - Java 类到 C# 类

php - 我的 sql 查询没有插入任何内容,我做错了什么?

php - 哪个数据库设计更好?

MySQL IN 子句特殊查询

java - 当仅设置 id 而不是首先从数据库获取对象时,一对多不会在没有引用的情况下更新

java - 为什么我收到以下 Selenium "The path to the driver executable must be set by the webdriver.chrome.driver system property"错误

php - jQuery UI 的 "datepicker"模块日期无法保存到 MySQL

python - 如何在 python 中逐行获取 MySQL ResultSet

sql - 当使用 SQL 可能存在重复时如何只选择不同的行?