【问题标题】:Select value from database with date condition从具有日期条件的数据库中选择值
【发布时间】:2014-05-27 12:44:32
【问题描述】:

我有一个 JComboBox 包含月份(九月,七月...) 和一个 jTable 以及数据库中的一个表 (Bills),其中包含 (Id bill , date , products ..)

我希望当像 september 从 jComboBox 中选择一个值时,它会在 9 月为我提供所有产品。

日期格式如 2014/May/27 14:31:04

我尝试了这段代码,但它没有工作,因为在 java 中我无法使用:

String sql1 = "select Products from Bills where Date LIKE "?????+jComboBox1.getSelectedItem()+*" ";

(它给出一个错误,我无法编译)

代码:

try

{

    Class.forName(driver).newInstance();

    Connection con = (Connection)DriverManager.getConnection(url,user,pass);

    String sql1 = "select Products from Bills where Date LIKE "?????+jComboBox1.getSelectedItem()+* " ";

    PreparedStatement pst = con.prepareStatement(sql1);

    ResultSet rs = (ResultSet) pst.executeQuery(sql1);

    jTable1.setModel(DbUtils.resultSetToTableModel(rs));

}
catch( Exception e){

    JOptionPane.showMessageDialog(null, e);

}

【问题讨论】:

  • 最佳实践,提出查询,并签入数据库,然后继续

标签: java database date jtable jcombobox


【解决方案1】:
String sql1 = "select Products from Bills where Date LIKE "?????+jComboBox1.getSelectedItem()+* " ";

为什么会这样??问号是什么?

应该是这样的:

String sql1 = "select Products from Bills where Date LIKE '"+jComboBox1.getSelectedItem()+ "'";

【讨论】:

  • 是的,我知道,但日期格式是 2014/May/27 14:31:04 ,日期类型是字符串,问题是条件是:String sql1 = "select Products from Bills where日期 LIKE ????'"+jComboBox1.getSelectedItem()+"'*";但没用
  • 嗯.. 你应该用 SimpleDateFormat 格式化你的日期 这是一个很好的教程:mkyong.com/java/java-date-and-calendar-examples 类似的东西:SimpleDateFormat("mm");此外,在您这样做之后,您的字符串将是:“select Products from Bills where Date LIKE '????/"+jComboBox1.getSelectedItem()+ "*'";类似的东西.. 但我建议使用preparedStatment 这是一个很好的教程mkyong.com/jdbc/…
  • 它不能工作,因为 SQL 通配符是 '%' 而不是 '*',所以你的查询应该是 "select Products from Bills where Date LIKE '%"+jComboBox1.getSelectedItem() + "%'"; ...但同样,不要把 sql 混在一起,使用参数。
【解决方案2】:

你在比较苹果和梨。日期只能与匹配类型进行比较。因此,如果该列是日期类型,则不能对其使用字符串比较(实际上是 LIKE)。

你准备好的语句应该看起来有点像

...
Date d = new SimpleDateFormat("yyyy/mm/dd hh:mm:ss").parse(jComboBox1.getSelectedItem());
PreparedStatement pst = con.prepareStatement("SELECT PRODUCTS FROM BILLS WHERE DATE = :dv");
pst.setDate("dv", d);
...

否则,您将在创建无效 SQL 时遇到麻烦,或者 - 更糟糕的是 - 使您的软件受到 SQL 注入的威胁(安全问题)。

编辑:日期算法总是带有数据库供应商的特殊风格。您应该检查数据库手册以获取正确的操作数。例如,DB2 允许内联转换不带任何操作数的日期。有关示例,请参见 SQL query to select dates between two dates

【讨论】:

  • 日期列是字符串类型,日期来自:2014/May/27 14:31:04,因此我使用 LIKE " ?????+jComboBox1.getSelectedItem()+ * "
  • 好的,然后忘记日期转换-尽管使用错误的类型不是好的设计;-) 如果您只是将值设为 '%Sep%',则“DATE LIKE :dv”可以工作
猜你喜欢
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 2013-08-19
  • 1970-01-01
  • 2016-07-19
相关资源
最近更新 更多