-4

当我尝试将表单中的数据添加到我的数据库时,它给了我一个错误

例外

org.apache.jasper.JasperException: java.lang.NumberFormatException: null 根本原因

java.lang.NumberFormatException:空

This is my code

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%@page import="java.util.*"%>
<%@page import="java.io.*" %>
<%
    String firstName = request.getParameter("firstName");
    String secondName = request.getParameter("secondName");
    String gender = request.getParameter("gender");
    String address = request.getParameter("address");
    String city = request.getParameter("city");
    String country = request.getParameter("country");
    int zip = Integer.parseInt(request.getParameter("zip"));
    int mobileNo = Integer.parseInt(request.getParameter("mobileNo"));
    int homePhone = Integer.parseInt(request.getParameter("homePhone"));
    String eMail = request.getParameter("eMail");

    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testproject", "root", "123456");
        Statement st = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        ps = con.prepareStatement("INSERT INTO studentregform (firstName, secondName, gender, address, city, country, zip, mobile, homePhone, email) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

        ps.setString(1, firstName);
        ps.setString(2, secondName);
        ps.setString(3, gender);
        ps.setString(4, address);
        ps.setString(5, city);
        ps.setString(6, country);
        ps.setInt(7, zip);
        ps.setInt(8, mobileNo);
        ps.setInt(9, homePhone);
        ps.setString(10, eMail);

        int result = ps.executeUpdate();




    } catch (Exception e) {
        //out.println("Data not inserted");
        throw new Error(e);
    }

%>

谁可以帮我这个事?谢谢你。

4

2 回答 2

2

java.lang.NumberFormatException: null似乎是一个明确的指针,表明您正在尝试将 nullString参数转换为 an Integer,或者 theString不是有效数字。

检查以下行中的空值/无效整数:

int zip = Integer.parseInt(request.getParameter("zip"));
int mobileNo = Integer.parseInt(request.getParameter("mobileNo"));
int homePhone = Integer.parseInt(request.getParameter("homePhone"));

另外,我建议使用Integer,以便您仍然可以将它们传递给它们PreparedStatement,以防它们为空/由于其格式不正确而无法初始化String

于 2012-09-18T17:52:45.800 回答
2

这三行之一似乎给您带来了问题;

int zip = Integer.parseInt(request.getParameter("zip"));
int mobileNo = Integer.parseInt(request.getParameter("mobileNo"));
int homePhone = Integer.parseInt(request.getParameter("homePhone"));

你确定它们都是完全数字的吗?如果其中一个为空、null、未设置或具有任何类型的分隔符,如1-800-123-4567,则不能将其存储为数字并Integer.ParseInt()会抛出NumberFormatException.

编辑:你说你的电话号码是 10 位数字,完全是数字。尽管如此,您还是会遇到问题,因为 JavaInteger没有那么高的精度。事实上,它不能存储任何大于约 20 亿的数字。

于 2012-09-18T17:53:37.247 回答