Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query MySQL DB using preparedStatement.setDate

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);

I am getting an error Tomcat Error

Can anyone help me with this, I need to query mySQL db where date = input in html

enter image description here

like image 440
mohit sharma Avatar asked Dec 11 '15 07:12

mohit sharma


2 Answers

No, skip the Date part; simply use the string. Let's see the value of (String date ).

MySQL is happy if you can end up with ... tag_data_date = '2015-12-11'.

If String date looks like '2015-12-11', then the conversion to Date is unnecessary.

like image 82
Rick James Avatar answered Nov 20 '22 12:11

Rick James


I have presented a solution. As you have not mentioned much about your DB structure, so ,

Consider test as database name, and consisting of table tag_data having two columns id and tag_data_date as shown below.

 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;

Also consider data in table as

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

And your java class as below

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;

}

}
like image 2
Naruto Avatar answered Nov 20 '22 12:11

Naruto