devloper
devloper

Reputation: 47

Getting error in Select from MYSQL

Getting error in Select from MYSQL on the line ResultSet rs = st.executeQuery(fetch_title);

Error msg : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':09:53' at line 1

String test = "27-May-2016 11:09:53";
String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time="+test+"";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(fetch_title);

Upvotes: 0

Views: 121

Answers (3)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

Your code is unsafe because it is conducive to SQL Injection attacks, you need to use a PreparedStatement instead as next:

String test = "27-May-2016 11:09:53";
PreparedStatement ps = connection.prepareStatement(
    "SELECT title FROM competitor_analysis WHERE cron_date_time=?"
);
ps.setString(1, test);
ResultSet rs = ps.executeQuery();

This approach has 2 main advantages:

  1. It is safer as mentioned above
  2. It is less error prone, as you don't have to escape the value explicitly anymore since it will be managed by the driver itself

Upvotes: 3

Otterbein
Otterbein

Reputation: 544

You have to declare the string in your MySQL query as a string; you aren't doing this which results in the error.

So you need to insert in '' in your case.

So you could do it like this:

String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time='"+test+"'";

Upvotes: 3

Paul Stanley
Paul Stanley

Reputation: 4098

Wrap up your date in speech marks in the query.

String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time='"+test+"'";

Upvotes: 5

Related Questions