我正在尝试使用选择查询根据来自网页的输入从我的 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);
最佳答案
这里有三个提示:
- 使用
prepareStatement
、占位符和绑定(bind)参数。 - 我认为你的意思是
COALESCE(fieldname, '')
而不是ISNULL(fieldname)
- 密切关注数据类型。我不确定 MySQL 如何将字符串作为 boolean 值处理,因为它们实际上并没有真正的 native boolean 类型(我认为 iirc 内部使用整数)。
第一步是模拟您的查询并在您的 rdbms 中的命令行中尝试它,并确保它执行您希望它执行的操作。先解决这个问题。然后使用 prepareStatement
和绑定(bind)参数重写。
不清楚这个查询在您的代码示例中应该做什么,所以很遗憾,这可能是我们能做的最好的事情。
关于java - 使用 AND 和 Where 从网页传递空字符串以选择查询时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41760051/