简体   繁体   English

使用c#从字符串转换日期和/或时间从字符串转换时失败,以便检查SQL Server数据库中的表

[英]Conversion failed when converting date and/or time from character string, using c# in order to check a table in SQL Server database

I am beginner in C# and I am developing an import system. 我是C#的初学者,正在开发一个导入系统。 In the code below I am trying to check if the date in the imported Excel file corresponds to the first or the second half year. 在下面的代码中,我试图检查导入的Excel文件中的日期是否对应于上半年或下半年。 Before the actual import, all registrations need to be deleted. 在实际导入之前,需要删除所有注册。 The code works fine but when I am executing the delete command I get an error: 代码工作正常,但是当我执行删除命令时,出现错误:

Conversion failed when converting date and/or time from character string 从字符串转换日期和/或时间时转换失败

Please help! 请帮忙!

PS: I have read the other posts about this error but I couldn't identify similarities with my code. PS:我已经阅读了有关此错误的其他文章,但无法确定与我的代码的相似之处。

Thank you! 谢谢!

string input = (string)table.Rows[2][27];
string neededDate = input.Substring(29);
string getmonth = input.Substring(32, 2);
string getyear = input.Substring(35, 4);

if (int.Parse(getmonth) <= 6 && int.Parse(getyear) == DateTime.Now.Year)
{
    var date1 = DateTime.Today;
    var year = date1.Year;

    DateTime start1 = new DateTime(year, 1, 1);
    DateTime end1 = new DateTime(year, 6, 30);

    db.ExecuteCommand("Delete from Table where Date between '" + start1 + "' AND '" + end1 +"'");                  
}
else if (int.Parse(getmonth) > 6 && int.Parse(getyear) == DateTime.Now.Year)
{
    var date2 = DateTime.Today;
    var year = date2.Year;

    DateTime  start2 = new DateTime(year, 7, 1);
    DateTime  end2 = new DateTime(year, 12, 31);

    db.ExecuteCommand("Delete from Table where Date  between '" + start2 + "' AND '" + end2 + "'");                     
}
else
{
    Console.Write("");
}

A couple of issues and observations for you. 给您一些问题和意见。

Why are you casting the value (row 2, column 27) to a string? 为什么将值(第2行,第27列)转换为字符串? Is it not a DateTime value already? 它不是DateTime值吗? If not, it probably should. 如果没有,可能应该。 This would remove the need for you to manually parse the data. 这将消除您手动解析数据的需要。 By manually parsing the data, you are not taking into account different DateTime formats. 通过手动解析数据,您无需考虑其他DateTime格式。 eg 例如

DateTime input = DateTime.Parse(table.Rows[2][27].ToString());

You can check for null values using: 您可以使用以下方法检查空值:

table.Rows[2].IsNull(27);

Is column 27 the [Date] column you reference in your delete statement? 第27栏是否是您在delete语句中引用的[Date]栏? If it's a string, then you'll have to cast the column and the values to DateTime types to use the BETWEEN syntax. 如果是字符串,则必须将列和值转换为DateTime类型以使用BETWEEN语法。

When dealing with dates, try specify the correct format SQL Server and .Net have different date formats by default. 处理日期时,请尝试指定正确的格式SQL Server和.Net默认情况下具有不同的日期格式。

You should also use parameterized SQL, not string concatenation as it leaves you potentially open to sql injection. 您还应该使用参数化的SQL,而不要使用字符串连接,因为它可能使您有可能进行sql注入。

DELETE FROM [Table] WHERE [Date] BETWEEN @StartDate AND @EndDate

Its probably due to a wrong date format used. 这可能是由于使用了错误的日期格式。 I believe that using .ToString("yyyy-MM-dd") on the dates will work for you. 我相信在日期上使用.ToString("yyyy-MM-dd")将对您.ToString("yyyy-MM-dd")

db.ExecuteCommand("Delete from Table where Date between '" + start1.ToString("yyyy-MM-dd")
                   + "' AND '" +  end1.ToString("yyyy-MM-dd") +"'");

But, using these kind of queries is considered bad-practice and can lead to sql-injection (although not in your specific case because the data is not coming from the users). 但是,使用这种类型的查询被认为是不好的做法,并且可能导致sql注入(尽管在您的特定情况下不是这样,因为数据不是来自用户的)。

You should start using parameterized queries instead: 您应该开始使用参数化查询:

SqlConnection con = new SqlConnection(connectionString);

var command = con.CreateCommand();
command.CommandText = "Delete from Table where Date between @start AND @end";
command.Parameters.Add("@start", SqlDbType.DateTime).Value = start1;
command.Parameters.Add("@end", SqlDbType.DateTime).Value = end1;
command.ExecuteNonQuery();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将C#datetime发送到SQL Server-错误“从字符串转换日期和/或时间时转换失败” - Send C# datetime to SQL Server - error “Conversion failed when converting date and/or time from character string” 从C#中的字符串SQL转换日期和/或时间时转换失败 - Conversion failed when converting date and/or time from character string SQL in c# 从字符串 SQL (c#) 转换日期或时间时,日期时间转换失败 - datetime conversion failed when converting date or time from character string SQL (c#) C#“从字符串转换日期/时间时转换失败”但查询在服务器上运行时效果很好 - C# "Conversion failed when converting date/time from character string" But query works well when run on server 从字符串转换日期和/或时间时,C#转换失败 - C# Conversion failed when converting date and/or time from character string 从字符串C#转换日期和/或时间时转换失败 - Conversion failed when converting date and/or time from character string C# 从C#中的字符串转换日期和/或时间时转换失败 - Conversion failed when converting date and/or time from character string in C# 从字符串转换日期时,SQL / C#转换失败 - SQL / C# Conversion failed when converting date from character string SQL Server“从字符串转换日期和/或时间时转换失败。” 从 WinForm DateTimePicker 插入日期值时 - SQL Server 'Conversion failed when converting date and/or time from character string.' when inserting date values from WinForm DateTimePicker 使用日期时间选择器从字符转换日期和/或时间时,C# 转换失败 - C# Conversion failed when converting date and/or time from character with a date time picker
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM