Java 日期格式错误
我正在使用 JDatechooser netbeans swing 插件进行桌面应用程序开发。默认情况下,其日期格式为 mm/dd/yy,但它不是数据库所需的格式。我需要将其转换为 yyyy-mm-dd 格式。我尝试使用 SimpleDateformat 类,但出现以下错误: com.mysql.jdbc.MysqlDataTruncation: 数据截断:日期值不正确:第 1 行的列 'registered_date' 为 '8/29/11'
谁能给我一个好的解决方案来正确执行此操作
谢谢
I am using JDatechooser netbeans swing plugin for my desktop app development. By default its dateformat is mm/dd/yy but its not the format which the db required. I need to convert it to the yyyy-mm-dd format. I tried with SimpleDateformat class and it gives me the following error: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '8/29/11' for column 'registered_date' at row 1
can anyone give me a good solution to do this properly
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的数据库根本不需要特定的日期格式 - 您首先不应该将数据作为字符串插入。您应该使用准备好的语句并使用
setDate
。理想情况下,您应该执行尽可能少的字符串转换 - 从JDateChooser
中获取值时不需要进行字符串转换,并且在插入数据库时也不需要进行字符串转换:(请注意, 确实可能需要牢记时区,但那是另一回事......您可以调用
setDate
重载,它也需要日历。)如果您已经插入(或查询)数据构建包含值的完整 SQL 语句时,您应该立即停止这样做。您不仅会遇到此类转换问题,而且还会面临 SQL 注入攻击。始终使用准备好的语句并将任何参数指定为参数,而不是将它们包含在 SQL 中。
Your database doesn't require a particular date format at all - you shouldn't be inserting the data as a string in the first place. You should use a prepared statement and use
setDate
. Ideally you should perform as few string conversions as possible - you don't need one when getting the value out of theJDateChooser
, and you don't need one when inserting into the database:(Note that you do potentially need to bear time zones in mind, but that's a different matter... you can call a
setDate
overload which takes a calendar too.)If you've been inserting (or querying) data by constructing a full SQL statement including the values, you should stop doing that right away. Not only do you have this sort of conversion issue, but you also open yourself up to SQL injection attacks. Always use a prepared statement and specify any parameter as parameters rather than including them in the SQL.
试试这个:
在这里查看相关的答案:
如何解析日期?< br>
Java 日期格式?
将 MySql DateTime 类型转换为更友好的类型
如何将java日期类型存储到mysql日期类型?< /a>
将日期转换为 MYSQL 日期格式
如何将字符串中的日期转换为Sql日期?
如何将当前日期设置为 MySQL 日期列Java?
Try this:
See related SO answers here:
How to parse a date?
Java date formatting?
Converting MySql DateTime type into something more friendly
how to store java date type to mysql date type?
Convert Date into MYSQL Date Format
How to convert Date in String to Sql date?
How to set Current date to MySQL date column from Java?