问题描述
我正在开发一个Web应用程序,其中数据将在客户端和客户端之间传输。服务器端。
I am working on a web application in which data will be transfer between client & server side.
我已经知道JavaScript int!= Java int。因为,Java int不能为null,对吧。
现在这是我面临的问题。
I already know that JavaScript int != Java int. Because, Java int cannot be null, right.Now this is the problem I am facing.
我将Java int变量更改为Integer。
I changed my Java int variables into Integer.
public void aouEmployee(Employee employee) throws SQLException, ClassNotFoundException
{
Integer tempID = employee.getId();
String tname = employee.getName();
Integer tage = employee.getAge();
String tdept = employee.getDept();
PreparedStatement pstmt;
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/general";
java.sql.Connection con = DriverManager.getConnection(url,"root", "1234");
System.out.println("URL: " + url);
System.out.println("Connection: " + con);
pstmt = (PreparedStatement) con.prepareStatement("REPLACE INTO PERSON SET ID=?, NAME=?, AGE=?, DEPT=?");
pstmt.setInt(1, tempID);
pstmt.setString(2, tname);
pstmt.setInt(3, tage);
pstmt.setString(4, tdept);
pstmt.executeUpdate();
}
我的问题在这里:
pstmt.setInt(1, tempID);
pstmt.setInt(3, tage);
我不能在这里使用整数变量。我尝试使用 intgerObject.intValue();
但它使事情变得更复杂。我们还有其他转换方法或转换技巧吗?
I cant use the Integer variables here. I tried with intgerObject.intValue();
But it makes things more complex. Do we have any other conversion methods or conversion techniques?
任何修复都会更好。
推荐答案
正如其他地方所写:
- 对于Java 1.5及更高版本,你不需要需要做(几乎)任何事情,它由编译器完成。
- 对于Java 1.4及更早版本,使用
Integer.intValue()
将Integer转换为int。
- For Java 1.5 and later you don't need to do (almost) anything, it's done by the compiler.
- For Java 1.4 and before, use
Integer.intValue()
to convert from Integer to int.
但是你写的时候, Integer
可以为null,所以这是明智的在尝试转换为 int
之前检查(或冒险获得 NullPointerException
)。
BUT as you wrote, an Integer
can be null, so it's wise to check that before trying to convert to int
(or risk getting a NullPointerException
).
pstmt.setInt(1, (tempID != null ? tempID : 0)); // Java 1.5 or later
或
pstmt.setInt(1, (tempID != null ? tempID.intValue() : 0)); // any version, no autoboxing
使用默认值零,也可以什么都不做,显示警告或......
我大多不喜欢不使用自动装箱(第二个样品线)所以我很清楚我是什么我想这么做。
I mostly prefer not using autoboxing (second sample line) so it's clear what I want to do.
这篇关于如何将Integer转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!