PreparedStatement中的日期字符串 [英] String to Date in a PreparedStatement

查看:57
本文介绍了PreparedStatement中的日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PreparedStatement中使用setDate(),但是我的日期格式为2008-07-31.代码是:

I am trying to use setDate() in a PreparedStatement, however the date that I have is in the format of 2008-07-31. The code is:

 pstmt.setDate(f++, (Date) DateFormat.getDateInstance(DateFormat.DEFAULT).parse(value.substring(0, 10)));

但是,它给了我错误:

Exception in thread "main" java.text.ParseException: Unparseable date: "2008-07-31"

这是为什么?

推荐答案

您需要确保默认的DateFormat为 yyyy-MM-dd 格式(通常是OS中的配置),或者您可以使用 SimpleDateFormat java.sql.Date 来解析日期字符串.

You need make sure the default DateFormat is in yyyy-MM-dd format (usually it's a config in OS), or you can use SimpleDateFormat or java.sql.Date to parse date string.

java.util.Date d;
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
d = sdf.parse ("2008-07-31");

// or
d = java.sql.Date.valueOf ("2008-07-31");

或者,如果基础数据库驱动程序支持将 VARCHAR / CHAR 转换为 DATE ,则可以将参数设置为String.

or, you could just set parameter as String, if the underlying database driver support the VARCHAR/CHAR to DATE conversion.

这篇关于PreparedStatement中的日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆