Insert integer from a jsp form into a database table?

Dia picture Dia · Jun 24, 2012 · Viewed 12.8k times · Source

See my code below...

//connect
//reading params from the form
String name = request.getParameter("name");
String year_prime = request.getParameter("year");
int year = Integer.parseInt(year_prime);

//inserting the params into table Students
stmt.executeUpdate("insert into students(name,year) values('"+name+"', year)");

//close connection

I am trying to get the year value, which is an int, and insert it into a database table. However I am getting an error, and the INSERT methods only seem to work with Strings. Could someone please help me with this problem.

Answer

KV Prajapati picture KV Prajapati · Jun 25, 2012

You should have to use PreapredStatement. From your post I can see you have incorrect value for VALUES() set.

stmt.executeUpdate("insert into students(name,year) values ('" + name + "'," + year ")");

It will be easy and safe to perform database operation with PreparedStatement:

String sql="insert into students(name,year) values (?,?)";
PreparedStatement statement=cn.prepareStatement(sql);
statement.setString(1,name);
statement.setInt(2,year);
statement.executeUpdate();