[英]java.sql.SQLException: Cannot insert the value NULL into column
[英]how to insert null value into datetime column in sql with java
有谁知道如何在sql中的数据库中将null值设置为datetime列? 我尝试将String设置为null: String date = null;
但我会得到这个错误:
java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting datetime from character string
。
此外,我尝试通过简单地声明它(String date;)来将我的字符串设置为无值。 然而,这最终会将日期设定为1900年1月1日。
我为程序用户使用了3个下拉框来选择每个月,日和年。
DateNew newdateprocessed;
int b, c;
String d;
//First I took the values from each drop down box.
b = Date_Processed_Month_Mod.getSelectedIndex();
c = Date_Processed_Day_Mod.getSelectedIndex();
d = Date_Processed_Year_Mod.getSelectedItem().toString();
newdateprocessed = new DateNew(b, c, d);
//Then I used these values in a separate function to put them all together as just one string
public class DateNew extends Object {
String newdate;
String monthword, newdateword;
int check=0;
public DateNew (int month, int day, String year) {
//newdate = ""+ month + "/" + day + "/" + year;
if (month == 0 | day == 0 | year.equals("Year")) {
newdate=null;
check = 1;
}
else {
switch (month) {
case 1:
monthword="January";
break;
case 2:
monthword="February";
break;
case 3:
monthword="March";
break;
case 4:
monthword="April";
break;
case 5:
monthword="May";
break;
case 6:
monthword="June";
break;
case 7:
monthword="July";
break;
case 8:
monthword="August";
break;
case 9:
monthword="September";
break;
case 10:
monthword="October";
break;
case 11:
monthword="November";
break;
case 12:
monthword="December";
break;
}
newdateword= monthword + " " + day + ", " + year;
newdate = ""+ month + "/" + day + "/" + year;
}
check=month;
}
public String newdate() {
return newdate;
}
public int newdatecheck(){
return check;
}
public String newdateword(){
return newdateword;
}
最后,我将newdateprocessed.newdate()提供给我的数据库中的列。 如果用户选择日期,它会正常工作,但如果他们没有选择我会收到错误的日期,这就是为什么我试图找到一种能够放置空值的方法。
试着打电话
setNull(index,java.sql.Types.DATE)
例如
String query = "UPDATE Licenses Set Date_Processed = ?";
PreparedStatement queryStatement = (PreparedStatement)connection.prepareStatement(sql);
queryStatement.setNull(1, java.sql.Types.Date);
为什么是字符串? 如果是日期时间列,您可以尝试:
Date date = null;
您似乎将一个字符串传递给您的数据访问代码,该代码存储在datetime列中,因此您依靠DBMS来解释字符串值并将其转换为日期时间。 这样就无法处理空值,因此您将不得不改变执行此操作的方式来实际传递兼容的数据类型,如Date实例。
尝试使用setDate方法(并传入null)而不是setString方法。
我想出了该怎么做。 我用来更新我的数据库的查询最初是这样的:
String query = "UPDATE Licenses Set Date_Processed = '" + newdateprocessed.newdate() + "'";
我在查询中取出单引号并将查询更改为:
String query = "UPDATE Licenses Set Date_Processed =" + newdateprocessed.newdate();
并在我的代码中设置我的DateNew函数中newdate的值,如果它为null我将其设置为:
newdate = "NULL";
如果不是我将它设置为:
newdate = "'" + month + "/" + day + "/" + year + "'";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.