I have 80000 recodes that are need to insert into database especially in table: temp(ts, temp) temp is INT.
The problem is almost 20000 recodes are null, so I am wondering how to insert NULL into DB when dataType is INT.
I tried this:
String val = null;
//insert(ts, val) into temp
String sql = "INSERT INTO temp" + "(val)" + " VALUES" + "('" + val + "')";
Statement st = (Statement) conn.createStatement();
count = st.executeUpdate(sql);
unfortunately insert is failure. Print out the exception message:
Incorrect integer value: 'null' for column 'val' at row 1"
Wish someone can help me with it. Thank you.
You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL);
But the short answer is: yes, int columns can have NULL values.
You just put NULL instead of value in INSERT statement. Show activity on this post. Show activity on this post. The optimal solution for this is provide it as '0' and while using string use it as 'null' when using integer.
Let's look at an example of how to use MySQL IS NULL in a SELECT statement: SELECT * FROM contacts WHERE last_name IS NULL; This MySQL IS NULL example will return all records from the contacts table where the last_name contains a NULL value.
You should use a PreparedStatement
and use setNull(int, int)
:
String sql = "INSERT INTO temp(val) VALUES (?)";
PreparedStatement st = con.prepareStatement(sql);
if (/* int value is not null */) {
st.setInt(1, value);
} else {
set.setNull(1, Types.INTEGER);
}
count = st.executeUpdate();
As an alternative to Mark Rotteveel's answer, you can also use PreparedStatement.setObject(int, Object, int).
You specify the SQL Type (3rd Parameter), and if the object is null, it inserts a null automatically. It's faster and easier.
String sql = "INSERT INTO temp(val) VALUES (?)";
PreparedStatement st = con.prepareStatement(sql);
st.setObject(1, value, Types.INTEGER);
count = st.executeUpdate();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With