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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:04:57  来源:igfitidea点击:

Insert integer from a jsp form into a database table?

javajspjdbcinsert-statement

提问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 yearvalue, 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:

以下链接可能会帮助您了解基础知识和工作示例:

  1. http://www.tutorialspoint.com/jdbc/jdbc-statements.htm
  2. http://www.tutorialspoint.com/jdbc/statement-object-example.htm
  1. http://www.tutorialspoint.com/jdbc/jdbc-statements.htm
  2. 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 PreparedStatementinstead of a regular Statement. Also, use executeQuery()instead of executeUpdate().

使用 aPreparedStatement而不是常规Statement. 另外,使用executeQuery()代替executeUpdate().