将日期插入 SQL
我试图将日期插入 SQL 表中,但是当程序运行时出现以下错误。
从字符串转换日期和/或时间时转换失败。
string dateReleased = DateReleasedDate.Value.ToString("YYYY-MM-DD");
string myQuery = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, dateAdded, developerID, publisherID, consoleID) VALUES('"
+ GameNameTxt.Text + "', '" + GenreCombo.SelectedValue + "', '" + PlayersNUD.Value + "', '" + OnlineCombo.SelectedText + "', '"
+ dateReleased + "', 'GETDATE()', '" + DeveloperCombo.SelectedValue + "', '"
+ PublisherCombo.SelectedValue + "','" + ConsoleCombo.SelectedValue + "')";
I'm trying to insert a date into a SQL table, but it when the program runs it gives the following error.
Conversion failed when converting date and/or time from character string.
string dateReleased = DateReleasedDate.Value.ToString("YYYY-MM-DD");
string myQuery = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, dateAdded, developerID, publisherID, consoleID) VALUES('"
+ GameNameTxt.Text + "', '" + GenreCombo.SelectedValue + "', '" + PlayersNUD.Value + "', '" + OnlineCombo.SelectedText + "', '"
+ dateReleased + "', 'GETDATE()', '" + DeveloperCombo.SelectedValue + "', '"
+ PublisherCombo.SelectedValue + "','" + ConsoleCombo.SelectedValue + "')";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请使用参数化查询。当我看到用于构造 SQL 查询的字符串连接时,我的眼睛感到疼痛:
就
dateAdded
列而言,我只需将其从 INSERT 中删除,然后直接在 SQL 数据库中添加默认值。请注意如何直接传递
DateTime
实例并让 ADO.NET 处理格式。额外的好处是,您的代码可以安全地抵御 SQL 注入。Please use parametrized queries. My eyes hurt when I see string concatenations used to construct SQL queries:
As far as the
dateAdded
column is concerned I would simply remove it from the INSERT and add it a default value directly in the SQL database.Notice how you are directly passing
DateTime
instances and you leave ADO.NET handle the formats. As a bonus your code is safe against SQL injections.问题是您将 GETDATE() 放入单引号中。它正在尝试将字符串“GETDATE()”转换为日期。
The problem is you put GETDATE() into single-quotes. It is trying to convert the string 'GETDATE()' into a date.
在我看来,从 .net 将日期传递到 SQL 的最佳方法是使用 .ToOADate 函数。
该函数传入日期的数字表示形式,该表示形式适用于任何数据库日期时间\日期字段,无论区域设置如何。
为您提供的一些信息:ToOADate< /a>
The best way to pass a date into SQL from .net, IMO, is to use the .ToOADate function.
The function passes in a numerical representation of the date that will work on any database datetime \ date field regardless of the regional setup.
Some info for you: ToOADate