我正在开发一个Web应用程序,在该应用程序中,数据将在客户端和服务器端之间传输.
我已经知道JavaScript int!= Java int.因为,Java int不能为null,对吧.现在这是我面临的问题.
我将Java int变量更改为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();
}
Run Code Online (Sandbox Code Playgroud)
我的问题在这里:
pstmt.setInt(1, tempID);
pstmt.setInt(3, tage);
Run Code Online (Sandbox Code Playgroud)
我不能在这里使用Integer变量.我试过intgerObject.intValue();
但它让事情变得更复杂.我们还有其他转换方法或转换技术吗?
任何修复都会更好.
use*_*421 69
正如其他地方所写:
Integer.intValue()从Integer转换为int. 但是在你写的时候,一个Integer可以为null,所以在尝试转换为int(或冒险获得a NullPointerException)之前检查它是明智的.
pstmt.setInt(1, (tempID != null ? tempID : 0)); // Java 1.5 or later
Run Code Online (Sandbox Code Playgroud)
要么
pstmt.setInt(1, (tempID != null ? tempID.intValue() : 0)); // any version, no autoboxing
Run Code Online (Sandbox Code Playgroud)
* 使用默认值零,也可以什么也不做,显示警告或...
我大多不喜欢不使用自动装箱(第二个样品线)所以我很清楚我想做什么.
Col*_*inD 13
既然你说你使用的是Java 5,可以使用setInt与Integer因autounboxing:pstmt.setInt(1, tempID)应该只是罚款.在早期版本的Java中,您必须.intValue()自己调用.
相反的作品,以及...指派int到Integer将自动使int使用被autoboxed Integer.valueOf(int).
Java将Integer转换为int并自动返回(除非您仍然使用Java 1.4).
另一个简单的方法是:
Integer i = new Integer("10");
if (i != null)
int ip = Integer.parseInt(i.toString());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
254419 次 |
| 最近记录: |