【问题标题】:Null values automatically inserted when executing a query using JSP and MySQL使用 JSP 和 MySQL 执行查询时自动插入空值
【发布时间】:2013-07-20 21:07:09
【问题描述】:

当我执行下面的代码时,在每次插入之前,会自动用 Null 值填充一行,然后插入实际值。

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="style.css" type="text/css">
    <title>Connecting to a Data base</title>
</head>
<body>

     <%
     String connectionURL="jdbc:mysql://localhost:3306/jsp_test";
     Connection connection = null;
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     connection = DriverManager.getConnection(connectionURL, "root", "exeterblr");
     if(!connection.isClosed()) {
         out.println("Successfully connected to " + "MySQL server using TCP/IP...");
         }
     else
         {
         out.println("Cannot connect to DB");
         }
        String name=request.getParameter("name");
        String email=request.getParameter("email");
        String phone=request.getParameter("phone");
        PreparedStatement pstatement=null;
        int updateTable=0;
        String queryString = "INSERT INTO sample_info(name,email,phone) VALUES (?, ?, ?)";
        pstatement=connection.prepareStatement(queryString);
        pstatement.setString(1, name);
        pstatement.setString(2, email);
        pstatement.setString(3, phone);

        updateTable=pstatement.executeUpdate();
      %>



    <form method="post" action="index.jsp">
        <table>
            <tr>
            <td>Name</td><td><input type="text" name="name"></td>
            </tr>
            <tr>
            <td>Email</td><td><input type="text" name="email"></td>
            </tr>
            <tr>
            <td>Phone</td><td> <input type="text" name="phone"></td>
            </tr>

        </table>
        <input type="submit" value="Submit">
    </form>


</body>

当我插入一个值时,数据库包含以下内容:

Name Email Phone <br />
NULL NULL  NULL  <br />
ActualValue ActualValue Actual Value

【问题讨论】:

  • 第一个NULL 插入发生在您加载表单时,下一个有效插入发生在您提交时。您只需要在表单发布时执行插入。
  • 看看System.out.println(name + "===" + email + "===" + phone + "===" + )得到了什么

标签: mysql jsp jdbc


【解决方案1】:

您每次访问网页时都插入 (NULL,NULL,NULL),而不仅仅是在提交时。

【讨论】:

    【解决方案2】:

    您没有检查表单是否已提交,或者不只是触发插入 sql 以便插入空值。首先检查表单是否已提交,如果表单已提交,则插入,否则不插入。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多