Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert NULL in mysql especially INT dataType

Tags:

java

mysql

jdbc

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.

like image 622
Eric Avatar asked Aug 26 '13 17:08

Eric


People also ask

How do I insert NULL value in int data type?

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

Can int be NULL in MySQL?

But the short answer is: yes, int columns can have NULL values.

How do you store NULL in integer?

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.

How do you NULL in MySQL?

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.


2 Answers

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();
like image 169
Mark Rotteveel Avatar answered Sep 20 '22 18:09

Mark Rotteveel


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();
like image 31
Xithias Avatar answered Sep 19 '22 18:09

Xithias