VB 2005 中的日期时间问题
我正在使用 VB2005 和 SQL SERVER 2000。
PVAR_SQL_STR = "INSERT INTO GLR_US_PERIOD (ORG5_CODE,PERIOD_YEAR,PERIOD_CODE," _
"PERIOD_NO,FROM_DATE,TO_DATE,INSERT_USER,INSERT_DATE) VALUES " _
& "('" & PVAR_COMPANY_CODE & "' ,'" & TextBox1.Text & "','" & Serial1.Text & _
"'," & TextBox2.Text & ", '" + DateTimePicker1.Value.ToString("D") + "' ,'" + _
DateTimePicker2.Value.ToString("D") + "','" & PVAR_USER_CODE & "','" + _
Now.ToString("F") + "')"
从字符串转换日期时间时出现语法错误仅因为这部分:
Now.ToString("F")
为什么,我不知道,但是当我更改为
Now.ToString("D")
它时效果很好,但它只保存日期。我想插入日期和时间。
I am using VB2005 and SQL SERVER 2000.
PVAR_SQL_STR = "INSERT INTO GLR_US_PERIOD (ORG5_CODE,PERIOD_YEAR,PERIOD_CODE," _
"PERIOD_NO,FROM_DATE,TO_DATE,INSERT_USER,INSERT_DATE) VALUES " _
& "('" & PVAR_COMPANY_CODE & "' ,'" & TextBox1.Text & "','" & Serial1.Text & _
"'," & TextBox2.Text & ", '" + DateTimePicker1.Value.ToString("D") + "' ,'" + _
DateTimePicker2.Value.ToString("D") + "','" & PVAR_USER_CODE & "','" + _
Now.ToString("F") + "')"
Syntax error converting datetime from character string because of this part only:
Now.ToString("F")
Why, I do not know but when I change into
Now.ToString("D")
it works well but it saves the date only. I want to insert date and time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单的答案是根本不要尝试将其全部构建到 SQL 语句中。请改用参数化查询,并将参数值设置为
DateTime.Now
(或DateTime.UtcNow
)。参数化查询也是对 SQL 注入攻击的有效防护。将一般数据(尤其是用户提供的数据)直接插入到 SQL 语句中会导致灾难。
请参阅 文档有关
SqlCommand.Parameters
的详细信息 - 或查阅有关 ADO.NET 的任何不错的教程或书籍。The simple answer is not to try to build it all into the SQL statement at all. Use a parameterised query instead, and set the parameter value to
DateTime.Now
(orDateTime.UtcNow
) instead.Parameterised queries are also an effective guard against SQL injection attacks. Inserting general data (especially when given by users) into SQL statements directly is a recipe for disaster.
See the docs for
SqlCommand.Parameters
for more information - or consult just about any decent tutorial or book on ADO.NET.