使用preparedStatement.setDate查询MySQL数据库

时间:2015-12-11 07:03:28

标签: mysql tomcat jdbc prepared-statement

public java.util.List<Tag> getAlltagsByDate(String date ){

    DataSource dataSource = new DataSource();
    Connection conn = dataSource.createConnection();
    ResultSet resultSet = null;
    PreparedStatement stmt = null;
    Tag tags_Data = new Tag();
    String query = "select * from tag_data where tag_data_date  =  ?";
    try {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date nn  =df.parse(date);
        stmt = conn.prepareStatement(query);
        stmt.setDate(1, java.sql.Date.valueOf(date));
        resultSet = stmt.executeQuery(query);

我收到了错误消息 Tomcat Error

任何人都可以帮我这个, 我需要查询mySQL db,其中date = input in html

enter image description here

2 个答案:

答案 0 :(得分:4)

不,跳过Date部分;只需使用字符串。让我们看看(String date )的价值。

如果您最终可以使用... tag_data_date = '2015-12-11',那么MySQL很高兴。

如果String date看起来像2015-12-11&#39;,那么转换为Date是不必要的。

答案 1 :(得分:1)

我提出了一个解决方案。由于您没有提及您的数据库结构,所以,

测试视为数据库名称,并由包含两列id和tag_data_date的表 tag_data 组成,如下所示。

 CREATE TABLE `tag_data` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `tag_data_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

还要将表格中的数据视为

INSERT INTO `tag_data` (`id`, `tag_data_date`) VALUES
(1, '2015-12-20 00:00:00');

你的java课程如下

public class JDBCPreparedStatementExample {

private static final String DB_DRIVER = "com.mysql.jdbc.Driver"; //mysql driver class
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/test"; //connectionstring
private static final String DB_USER = "root"; //mysql username
private static final String DB_PASSWORD = "root"; //mysql password

public static void main(String[] argv) throws ParseException {

    try {

        getDateForDate("2015-12-20"); //time passed as arguement

    } catch (SQLException e) {

        System.out.println(e.getMessage());

    }

}
//Method to interact with DB and print data,this can be changed to return value of List<Key> as per your requirement
private static void getDateForDate(String date) throws SQLException, ParseException {

    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    java.util.Date dateCal  =df.parse(date); // parse date in String to Date Object
    String updateTableSQL = "select * from tag_data where tag_data_date  =  ?";

    try {
//get DB connection
        dbConnection = getDBConnection();
// Create preapared statement           
preparedStatement = dbConnection.prepareStatement(updateTableSQL);

        preparedStatement.setDate(1, new Date(dateCal.getTime()));//convert java.util.Date to java.sql.Date

        // execute update SQL stetement
        ResultSet resultSet = preparedStatement.executeQuery();
         while (resultSet.next()) {
              // It is possible to get the columns via name
              // also possible to get the columns via the column number
              // which starts at 1
              // e.g. resultSet.getString(2);
              int id = resultSet.getInt("id");
              Date tag_data_date = resultSet.getDate("tag_data_date");
              System.out.println("Date: " + tag_data_date);
              System.out.println("Comment: " + id);
            }

    } catch (SQLException e) {

        System.out.println(e.getMessage());

    } finally {

        if (preparedStatement != null) {
            preparedStatement.close();
        }

        if (dbConnection != null) {
            dbConnection.close();
        }

    }

}

private static Connection getDBConnection() {

    Connection dbConnection = null;

    try {

        Class.forName(DB_DRIVER);

    } catch (ClassNotFoundException e) {

        System.out.println(e.getMessage());

    }

    try {

        dbConnection = DriverManager.getConnection(
                        DB_CONNECTION, DB_USER,DB_PASSWORD);
        return dbConnection;

    } catch (SQLException e) {

        System.out.println(e.getMessage());

    }

    return dbConnection;

}

}