.net c#sql string到date转换错误

时间:2011-10-05 07:31:19

标签: c# .net asp.net

我在visual studio中使用SQL时出现了数据库错误。

我使用的数据库是一个普通的sql server数据库。 这是我的任务。

这是我的查询方法是我的webservice

 [WebMethod]
    public bool search(string ddate, string dairport, string aairport, string seat)
    {
        int seat2 = Convert.ToInt32(seat);
        DateTime date = Convert.ToDateTime(ddate);

        String query1 = "SELECT * FROM Flight_Schedule S WHERE S.departure_date = '24/09/2011'";

        using (SqlConnection connect = new SqlConnection(conn))
        {
            SqlCommand cmd = new SqlCommand(query1, connect);
            connect.Open();
            SqlDataReader result = cmd.ExecuteReader();
            try
            {
                if (result.Read())
                {
                    return true;
                }

            finally
            {
                result.Close();
                connect.Close();
                connect.Dispose();
            }
            return false;
        }

    }

普通查询没有问题,例如:

"SELECT * FROM Flight_Schedule S WHERE S.origin_airport_code = '" + dairport + "'";

错误:

System.Data.SqlClient.SqlException: Conversion failed when converting date and/or time from character string.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlDataReader.HasMoreRows()
   at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
   at System.Data.SqlClient.SqlDataReader.Read()
   at AirportService.AirportServices.search(String ddate, String dairport, String aairport, String seat) in C:\Users\XXXXX\Documents\Visual Studio 2010\Projects\WebService2\AirportService\AirportServices.asmx.cs:line 47

4 个答案:

答案 0 :(得分:7)

您应该在C#中处理日期时间解析逻辑(以您接受的格式),并将其作为参数传递,即

String query1 = "SELECT * FROM Flight_Schedule S WHERE S.departure_date = @departureDate"

并添加SqlParameter您想要的DateTime值;那样......没问题。没有解析数据库,没有注入风险。并且查询计划也重复使用。全面赢。

例如:

DateTime when = DateTime.Parse(ddate); // better to use ParseExact and formally state the format you are using
const string query1 = "SELECT * FROM Flight_Schedule S WHERE S.departure_date = @departureDate";

using (SqlConnection connect = new SqlConnection(conn))
{
    using (SqlCommand cmd = new SqlCommand(query1, connect))
    {
        cmd.Parameters.AddWithValue("departureDate", when);
        connect.Open();
        using (SqlDataReader result = cmd.ExecuteReader())
        {
           ... etc
        }
    }
}

答案 1 :(得分:1)

马克·格拉维尔绝对是对的。但试试这个:

"SELECT * FROM Flight_Schedule S WHERE S.origin_airport_code = '" + dairport.ToString("yyyyMMdd") + "'"; 

答案 2 :(得分:0)

您的错误显示“从字符串转换日期和/或时间时转换失败。”

替换此行

DateTime date = Convert.ToDateTime(ddate);

IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
DateTime theDateTime = DateTime.ParseExact(ddate, "mm-dd-yyyy", theCultureInfo);

试试这个......

答案 3 :(得分:-1)

作为使用SQL日期的最佳实践规则,如果必须在SQL查询中指定日期,请始终尝试使用ISO格式(yyyy-MM-dd)。在大多数情况下,它会阻止出现任何转换错误。

在您的代码中:

"SELECT * FROM Flight_Schedule S WHERE S.origin_airport_code = '" + ddate.ToString("yyyy-MM-dd") + "'"; 

克里斯