【问题标题】:How to insert Data to Database using JSP如何使用 JSP 将数据插入数据库
【发布时间】:2014-12-31 10:16:53
【问题描述】:

我知道这个问题已经被问过了,不幸的是,答案不能帮助我解决我的问题。

我有一个工作的 Mysql 数据库“测试”,我保存我的数据(只有字符串)。 以下代码显示了我的 <div>-Container ,我从中获取数据。

<form action="index.jsp" method="POST">
  <div .....>

   <input type"text" name="termin" />
   <input type="submit" value="submit" />

  </div>
</form>

我使用的 JSP 代码:

<%
int result = 0;
String name = request.getParameter("termin");


Termin t1 = new Termin();
result = t1.setTermin(name);
%>

第一次单击提交按钮时,它会将 NULL 添加到我的数据库中。如果我再次单击,它不会更改数据库。

有人知道发生了什么吗? 编辑:我的错它应该是名称而不是数据

public class Termin {
String URL = "jdbc:mysql://localhost:3306/test";
String username="root";
String pw = "root";

Connection con = null;
PreparedStatement stmt = null;
ResultSet res = null;

public Termin() {
    try {
        con = DriverManager.getConnection(URL,username,pw);


    }catch(SQLException e) {
        e.printStackTrace();
    }
}

public int setTermin(String tname) {
    int result = 0;
    try {
        stmt = con.prepareStatement(
                "INSERT INTO ver(TName) VALUES(?);");
        stmt.setString(1,tname);
        result = stmt.executeUpdate();
        stmt.clearParameters();
    }catch(SQLException e) {
        e.printStackTrace();
    }

    return result;
}

}

【问题讨论】:

  • 首先不要在jsp文件中使用java代码(scriptlet),其次发布你的Termin类的代码,你在哪里使用name
  • 也许这与您没有对 name 做任何事情有关?没有看到实现的其他部分,只能猜测......
  • 如果你能在Termin类中显示代码就好了。其他事情你在哪里使用名称查询。
  • 我应该将我的 Java 代码放在 JSP-FIle 中的什么位置?
  • 我发现问题出在哪里,当我加载页面时,我的输入字段为空,这就是为什么我的数据库中有这个空字符串。但是,如果我再次点击提交,它不起作用......

标签: java mysql jsp insert


【解决方案1】:

没有条件来检查名为termin 的参数是否为空。所以当你加载jsp页面时,java代码被执行,因为参数没有值,null被保存在数据库中。

【讨论】:

  • int 结果 = 0;字符串名称 = 新字符串(); if(request.getParameter("termin") != null) { name = request.getParameter("termin"); } 终端 t1 = 新终端();结果 = t1.setTermin(name);现在它正在保存一个空字符串,如果我再次单击提交按钮上的时间它仍然无法工作:)
猜你喜欢
  • 2021-08-31
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 2020-08-29
  • 2014-02-23
  • 2019-01-01
  • 1970-01-01
  • 2018-01-13
相关资源
最近更新 更多