In my application I passed date value (as string) as parameter to Servlet. In Servlet code, I converted the string to sql date as “2013-02-05” (yyyy-MM-dd).
Example: dat=”05/02/2013″ converted to sqlDate=”2013-02-05″.
My servlet code is
dat= request.getParameter("dat");
//dat="05/02/2013";
try
{
java.util.Date date=new SimpleDateFormat("dd/MM/yy").parse(dat);
//out.println(date);
sqlDate = new java.sql.Date(date.getTime());
//out.println(sqlDate);
}
catch(Exception e)
{
}
if(div_code!=null)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@xxx.xxx.x.xxx:xxx:pdsm", "test", "test");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("insert into offer1 values('"+r_code+"','"+v_name+"','"+vcode+"','"+div_code+"','"+sec_code+"','"+extent+"','"+phone+"','"+sqlDate+"','"+loan+"','"+seeds+"','"+offerno+"','"+loc+"')");
conn.setAutoCommit(true);
out.println("data inserted");
}catch(Exception e)
{
out.println(e);
}
}
When I’m calling this from android application, it shows error as “ORA-01861: literal doesn’t match format string“. The format I’ve used is shown correct result when I tested with sample input. But data didn’t get inserted.
What is the problem in my code? Why am I receiving this error? Do I need to convert further? If yes, then how?
Also, someone explain can I use pl/sql function (to_date()) in servlet? Because it is easy to convert date
Edit: Modified Code:
String query="insert into offer1('RCODE','OFFERNO','DAT') values(?,?,?)";
PreparedStatement ps=conn.prepareStatement(query);
ps.setString(1,r_code);
ps.setString(2,offerno);
ps.setDate(3,sqlDate);
ResultSet rs=ps.executeQuery();
out.println("data inserted");
First of all don’t frame your query like this (appending everything into a single string).
It is vulnerable to SQL injection See SQL injection
So better use
PreparedStatementas it will protect you from SQL injection and your conversion tasks for various values will be automatically taken care of.So if you have a
java.sql.DatevariablesqlDateand now you want to insert it in the database: then you need these simple steps:Now hope you can figure out how to do it for yourself.
For more information see this and this