[英]How do I insert a NULL value into a db table in java?
The problem is that I can't figure out how to insert a null value. 问题是我不知道如何插入空值。 The column is date and if it's empty it just adds the current date to the db by default, but I don't know how to leave it empty or null if the user doesn't specify a custom date.
该列是日期,如果为空,则默认情况下会仅将当前日期添加到数据库中,但是如果用户未指定自定义日期,我不知道如何将其保留为空或为null。
statement.executeUpdate("insert into table values(null, 100, 'text')");
This is the query. 这是查询。 I've tried to skip the first value, insert a null, insert empty string, a 0 value.
我试图跳过第一个值,插入一个空值,插入一个空字符串,一个0值。 nothing seems to do the trick.
似乎无济于事。
try the below code 试试下面的代码
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();
Use this form, where you specify what columns you intend to set: 使用此表单,在其中指定要设置的列:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
In your case: 在您的情况下:
insert into table (col2, col3) values (100, 'text')
(where of course col2 and col3 is the column names of your table) (当然,col2和col3是表的列名)
Edit: The date column (col1) will probably need the constraint "Default null" for this to work as you intended. 编辑:日期列(col1)可能需要约束“ Default null”才能按预期工作。
in your column_date uncheck NOT NULL then you can insert NULL VALUES 在column_date中取消选中NOT NULL,然后可以插入NULL值
simple code "INSERT INTO table_name
( field_name
) VALUES (NULL) 简单代码“ INSERT INTO
table_name
( field_name
)VALUES(NULL)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.