java 将jsp表单中的整数插入到数据库表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11177579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert integer from a jsp form into a database table?
提问by Dia
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.
我正在尝试获取year
值,即int
,并将其插入到数据库表中。但是我收到一个错误,INSERT 方法似乎只适用于Strings
. 有人可以帮我解决这个问题。
回答by adatapost
You should have to use PreapredStatement
. From your post I can see you have incorrect value for VALUES()
set.
您应该必须使用PreapredStatement
. 从您的帖子中,我可以看到您的VALUES()
set值不正确。
stmt.executeUpdate("insert into students(name,year) values ('" + name + "'," + year ")");
It will be easy and safe to perform database operation with PreparedStatement:
使用 PreparedStatement 执行数据库操作将既简单又安全:
String sql="insert into students(name,year) values (?,?)";
PreparedStatement statement=cn.prepareStatement(sql);
statement.setString(1,name);
statement.setInt(2,year);
statement.executeUpdate();
回答by Prakash K
The following links might help you with the basics and also with a working example:
以下链接可能会帮助您了解基础知识和工作示例:
- http://www.tutorialspoint.com/jdbc/jdbc-statements.htm
- http://www.tutorialspoint.com/jdbc/statement-object-example.htm
- http://www.tutorialspoint.com/jdbc/jdbc-statements.htm
- http://www.tutorialspoint.com/jdbc/statement-object-example.htm
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 Practicesfor you.
虽然我不会推荐并且在 JSP 中包含 JDBC 连接代码也不是一般做法,但为什么呢?这是适合您的Servlets 和 Jsp 最佳实践。
Hope this helps.
希望这可以帮助。
回答by carlspring
Use a PreparedStatement
instead of a regular Statement
. Also, use executeQuery()
instead of executeUpdate()
.
使用 aPreparedStatement
而不是常规Statement
. 另外,使用executeQuery()
代替executeUpdate()
.