I want insert a null value into database instead of inserting default primitive value.
I have a class
class Test
(
private int first;
private int second;
public Test() {}
public void setFirst(int val) {first = val;}
public void setSecond(int val) {second = val;}
public int getFirst() {return first;}
public int getSecond() {return second;}
)
I have some code that initialize Test class:
Test my = new Test(); my.setFirst(100);
so we have now: first = 100; second = 0; -- since I don't initialize it and it default to zero "0" for int.
Now I insert the data into database table Test ...
Create table Test
(
first number,
second number
)
Java call ...
Test my = new Test();
my.setFirst(100);
String sql = "INSERT INTO TEST VALUES(?,?)";
PrepareStatement ps = connection.prepareStatement(sql);
ps.setInt(1, my.getFirst()); // will insert 100
ps.setInt(2, my.getSecond()); // will insert 0
I want insert NULL into "second" field since Test.second is not set in my code. I use the following trick:
class Test
(
private int first = -999;
private int second = -999;
public Test() {}
public void setFirst(int val) {first = val;}
public void setSecond(int val) {second = val;}
public int getFirst() {return first;}
public int getSecond() {return second;}
)
Test my = new Test();
my.setFirst(100);
String sql = "INSERT INTO TEST VALUES(?,?)";
PrepareStatement ps = connection.prepareStatement(sql);
if (my.getFirst() == -999)
ps.setNull(1, java.sql.Types.INTEGER) // will insert NULL
else
ps.setInt(1, my.getFirst()); // will insert 100
if (my.getSecond() == -999)
ps.setNull(2, java.sql.Types.INTEGER) // will insert NULL
else
ps.setInt(2, my.getSecond()); // will insert 0
Does somebody has the best/nice solution to implement that ?
I get NullPointerException when use Integer, this is right since var is not initialized or I missed something here:
java.lang.NullPointerException
at UserQuiz.getFrom_flags_challenge_nid(UserQuiz:113)
UserQuiz. java
...
private Integer from_flags_challenge_nid;
public int getFrom_flags_challenge_nid() {
return from_flags_challenge_nid;
}
public void setFrom_flags_challenge_nid(int from_flags_challenge_nid) {
this.from_flags_challenge_nid = from_flags_challenge_nid;
}
...