Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

java - How to convert Integer to int?

I am working on a web application in which data will be transfer between client & server side.

I already know that JavaScript int != Java int. Because, Java int cannot be null, right. Now this is the problem I am facing.

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();
 }

My problem is here:

pstmt.setInt(1, tempID);

pstmt.setInt(3, tage);

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?

Any fix would be better.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As already written elsewhere:

  • 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.

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

or

pstmt.setInt(1, (tempID != null ? tempID.intValue() : 0));  // any version, no autoboxing  

* using a default of zero, could also do nothing, show a warning or ...

I mostly prefer not using autoboxing (second sample line) so it's clear what I want to do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...