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.
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();
The following links might help you with the basics and also with a working example:
Though I won't recommend and it is also not a general practice to include JDBC connection code in JSP, why? Here is the Servlets and Jsp Best Practices for you.
Hope this helps.
Use a PreparedStatement
instead of a regular Statement
. Also, use executeQuery()
instead of executeUpdate()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.