如何使用C#将日期(31.12.2016)从excel转换为SQL Server [英] How I convert date(31.12.2016) from excel to SQL server using C#

查看:102
本文介绍了如何使用C#将日期(31.12.2016)从excel转换为SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Excel工作表中选择数据,我想在sql server中插入它,但是日期给了我错误(从字符串转换日期和/或时间时转换失败。)



这是代码:



插入DATA_NOTIFICATIONS(Notification_id,Notification_date)

值(ds.Tables [0] .Rows [i] [11] +','+

ds.Tables [0] .Rows [i] [9] .ToString()+','+)



我尝试了什么:



i尝试使用datetime.ParseExact但它给了我同样的错误。

所以我怎么解决这个问题

i select data from excel sheet and i want insert it in sql server but the date gave me error (Conversion failed when converting date and/or time from character string.)

this is code:

insert into DATA_NOTIFICATIONS(Notification_id,Notification_date)
Values (ds.Tables[0].Rows[i][11] + "','" +
ds.Tables[0].Rows[i][9].ToString() + "','" +)

What I have tried:

i try used datetime.ParseExact but it's give me same error.
so how i solve it this problem

推荐答案

如果我正确理解你的情况,而不是直接将值连接到SQL声明你应该在insert语句中使用参数。



看一下正确执行数据库操作 [ ^ ]
If I understand your situation correctly, instead of concatenating the values directly to SQL statement you should use parameters in the insert statement.

Have a look at the examples in Properly executing database operations[^]


简单:永远不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。

将Excel值转换为DateTime - 假设它作为字符串从Excel中输入,它不应该 - 并通过参数直接将Datetime值传递给SQL而不是将其转换为字符串。
Simple: Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
Convert your Excel value to a DateTime - assuming it comes in from Excel as a string, which it shouldn't - and pass the Datetime value directly to SQL via a parameter instead of converting it to a string.


这篇关于如何使用C#将日期(31.12.2016)从excel转换为SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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