java.lang.NumberFormatException:使用JSP App和mySQL

时间:2014-04-14 15:58:53

标签: java mysql jsp

您在尝试从jsp应用程序向我的数据库插入数据时遇到上述错误

这是JSP代码

    <%@page contentType="text/html" pageEncoding="UTF-8"%>

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

<br>

<div class="navigator">
<a id="currenttab" href="index.jsp">Add</a>
<a href="delete.jsp">Delete</a>
</div>

<%
  String empfirstname = request.getParameter("empfirstname");
  String empsurname = request.getParameter("empsurname");
  String dpddept = request.getParameter("dpddept");
  String extensionno = request.getParameter("extensionno");
  String mobileno = request.getParameter("mobileno");
  String emailaddress = request.getParameter("emailaddress");
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  if (empsurname != null && empfirstname != null 
          && username != null && password != null) {
      Users.Worker.Insert(empfirstname,empsurname,dpddept,extensionno,
              mobileno,emailaddress,username,password);
  }
%>

<br> <br> <br>

    <form method='post' action='index.jsp'>
                    <table>
                        <tr><td>Please Enter your first name.</td>
                            <td><input type="text" id='empfirstname'></td></tr>
                        <tr><td>Please Enter your surname.</td>
                            <td><input type="text" id='empsurname'></td></tr>
                        <tr><td>Please Enter your Department.</td>
                            <td><input type="text" id='dpddept'></td></tr>
                        <tr><td>Please Enter your Extension Number.</td>
                            <td><input type="text" id='extensionno'></td></tr>
                        <tr><td>Please Enter your mobile Number.</td>
                            <td><input type="text" id='mobileno'></td></tr>
                        <tr><td>Please Enter your email Address.</td>
                            <td><input type="text" id='emailaddress'></td></tr>
                        <tr><td>Please Enter your email username.</td>
                            <td><input type="text" id='username'></td></tr>
                        <tr><td>Please Enter your email password.</td>
                            <td><input type="text" id='password'></td></tr>
                        <tr><td><input type="submit" name="submit"/></td></tr>
                    </table></form>
</body>
</html>

这是java源代码

    package Users;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Worker {

  static final String url = "jdbc:mysql://localhost:3306/users";

  public static void Insert(String empfirstname,String empsurname,
          String dpddept,String extensionno,String mobileno,
          String emailaddress,String username,String password) {
      try {

          String insert = "INSERT INTO users(empfirstname,empsurname,dpddept,extensionno,"
                  + "mobileno,emailaddress,username,password)" +
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

          Class.forName("com.mysql.jdbc.Driver");
          Connection con = DriverManager.getConnection(url, "root", "dpd2014");

          PreparedStatement ps = con.prepareStatement(insert);


          ps.setString(1, empfirstname);
          ps.setString(2, empsurname);
          ps.setString(3, dpddept);
          ps.setInt(4, Integer.parseInt(extensionno));
          ps.setString(5, mobileno);
          ps.setString(6, emailaddress);
          ps.setString(7, username);
          ps.setString(8, password);
          ps.executeUpdate();
          con.close();

      } catch (Exception ex) {
          Logger.getLogger(Worker.class.getName()).log(
                           Level.SEVERE, null, ex);
      }
  }

  public static List GetUsers() {

      List<String> list = new ArrayList<String>();

      try {

          Class.forName("com.mysql.jdbc.Driver");
          Connection con = DriverManager.getConnection(url, "root", "dpd2014");

          Statement stmt = con.createStatement();

          ResultSet result = stmt.executeQuery("SELECT * FROM users");



          while(result.next())
          {

             list.add(result.getString("empfirstname"));
             list.add(result.getString("empsurname"));
             list.add(result.getString("dpddept"));
             list.add(result.getString("extensionno"));
             list.add(result.getString("mobileno"));
             list.add(result.getString("emailaddress"));
             list.add(result.getString("username"));
             list.add(result.getString("password"));
          } 

          con.close();

      } catch (Exception ex) {
          Logger.getLogger(Worker.class.getName()).log( 
                           Level.SEVERE, null, ex);
      }
          return list;
  }

  public static void Delete(String employeeno) {
      try {

          String delete = "DELETE from users WHERE employeeno = ?";

          Class.forName("com.mysql.jdbc.Driver");
          Connection con = DriverManager.getConnection(url, "root", "dpd2014");
          PreparedStatement ps = con.prepareStatement(delete);

          ps.setString(1, employeeno);
          ps.executeUpdate();
          con.close();

      } catch (Exception ex) {
          Logger.getLogger(Worker.class.getName()).log( 
             Level.SEVERE, null, ex);
      }
  }
}

最后这是mysql表

 users
 (Employeeno int(11) AI PK
 empfirstname varchar(30)
 empsurname varchar(40)
 dpddept varchar(30)
 extensionno int(11)
 mobileno     varchar(30)
 emailaddress varchar(30)
 username varchar(30)
 password varchar(30))

我希望这是足够的信息,任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

来自PreparedStatement docs

  

注意:用于设置IN参数值的setter方法(setShort,setString等)必须指定与输入参数的已定义SQL类型兼容的类型。例如,如果IN参数的SQL类型为INTEGER,则应使用方法setInt。

您的extensionnomobilenoint,而不是varchar。但你是这样设置的:

ps.setString(5, extensionno);
ps.setString(6, mobileno);

他们应该是:

ps.setInt(5, extensionno);
ps.setInt(6, mobileno);
编辑:看起来Ravinder得到了完整的解决方案,请检查他的答案。

答案 1 :(得分:1)

java.lang.NumberFormatException字段的值输入可能会引发异常extensionno

你的表结构说明了

extensionno int(11) -- column position 5 in the table

您尝试将值设置为

ps.setString( 4, dpddept ); // this caused the error   
ps.setString( 5, extensionno ); // but not this  

setString( 4...导致了NumberFormatException 4th占位符适用于extensionno int(11)类型。{。}} 但是您要设置dpddept变量的值,该变量是varchar字符串。 当您尝试将String插入int数字类型时,数据库将抛出错误,如:

ERROR 1366 (HY000): 
  Incorrect integer value: 'sales' for column 'extensionno' at row 1

如何解决此问题

我们已根据sql语句中查询参数的 position 设置值,但不是基于表中的列位置

String insert = 
    "INSERT INTO users( empfirstname, empsurname, dpddept, extensionno, "
  + "mobileno, emailaddress, username, password )" 
  + "VALUES ( ?, ?, ?, ?, ?, ?, ?, ? )";

在上面的查询中有8个占位符(?) 这意味着您应该从set...1st参数8th 8个值 这些是insert查询中的占位符位置编号,而不是表格中的列位置

因此声明

ps.setString( 2, empfirstname );

错了。它应该是

ps.setString( 1, empfirstname );

查看文档说明的内容:

  

setString(int parameterIndex, String x) throws SQLException
       - parameterIndex - 第一个参数是1,第二个参数是2,...
       - x - 参数值

更改您的值设置器,如下所示:

ps.setString( 1, empfirstname ); // varchar string
ps.setString( 2, empsurname ); // varchar string
ps.setString( 3, dpddept ); // varchar string

// you can use setString on int type columns,
// but only when they are valid numbers
// ps.setString( 4, extensionno ); // int int
// or
ps.setInt( 4, Integer.parseInt( extensionno ) ); // int int

// ps.setString( 5, mobileno ); // int int
// or
ps.setInt( 5, Integer.parseInt( mobileno ) ); // int int

ps.setString( 6, emailaddress ); // varchar string
ps.setString( 7, username ); // varchar string
ps.setString( 8, password ); // varchar string

ps.executeUpdate();