問題描述
我正在開發(fā)一個 Web 應(yīng)用程序,在該應(yīng)用程序中,數(shù)據(jù)將在客戶端和客戶端之間傳輸.服務(wù)器端.
I am working on a web application in which data will be transfer between client & server side.
我已經(jīng)知道 JavaScript int != Java int.因為,Java int 不能為空,對.現(xiàn)在這是我面臨的問題.
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);
我不能在這里使用整數(shù)變量.我試過 intgerObject.intValue();
但它使事情變得更加復(fù)雜.我們還有其他轉(zhuǎn)換方法或轉(zhuǎn)換技術(shù)嗎?
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?
任何修復(fù)都會更好.
推薦答案
正如已經(jīng)在別處寫的:
- 對于 Java 1.5 及更高版本,您(幾乎)不需要做任何事情,它由編譯器完成.
- 對于 Java 1.4 及之前版本,使用
Integer.intValue()
將 Integer 轉(zhuǎn)換為 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
可以為空,因此在嘗試轉(zhuǎn)換為 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
* 使用默認(rèn)值零,也可以什么都不做,顯示警告或...
我大多不喜歡使用自動裝箱(第二個示例行),所以很清楚我想要做什么.
I mostly prefer not using autoboxing (second sample line) so it's clear what I want to do.
這篇關(guān)于如何將整數(shù)轉(zhuǎn)換為整數(shù)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!