如何解决将varchar数据类型转换为datetime数据类型导致值超出范围。该语句已终止。'

时间:2019-05-12 20:05:27

标签: c# sql-server datetime

我尝试将数据插入SQL Server,但由于错误而无法运行查询

  

System.Data.SqlClient.SqlException:'将varchar数据类型转换为日期时间数据类型会导致值超出范围。

我正在使用c#进行编码。

txtPlateNo.Text = vehicresult.results[0].plate.ToString();
lblDate.Text = DateTime.Now.ToShortDateString();
lblTime.Text = DateTime.Now.ToShortTimeString();

//string parkDate = lblDate.Text;
//DateTime newDate = Convert.ToString(parkDate.ToString("MMddyyyy"));
//string parkTime = lblTime.Text;
//DateTime newTime = Convert.ToDateTime(parkTime);

//label10.Text = newDate;
//string newDate2 = label10.Text.ToString();
//string newTime2 = newTime.ToString();

SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);
if (conn.State == System.Data.ConnectionState.Closed)
    conn.Open();
SqlDataReader dr;

SqlCommand cmd = new SqlCommand("SELECT * FROM pmsVehicleRecord WHERE clVehicPlateNo='" + txtPlateNo.Text + "'", conn);

dr = cmd.ExecuteReader();

if (dr.HasRows)
{
    while (dr.Read())
    {
        lblFullName.Text = dr["clFullName"].ToString();
        lblUsername.Text = dr["clUsername"].ToString();
        lblAddress.Text = dr["clAddress"].ToString();
        lblPaymentMethod.Text = dr["clPaymentMethod"].ToString();
    }

    dr.Close();
    SqlCommand cms = new SqlCommand("SELECT * FROM pmsParkingRecord WHERE parkVehicPlateNo ='" + txtPlateNo + "' AND parkDate='" + lblDate + "'", conn);
    dr = cms.ExecuteReader();

    if (dr.HasRows)
    {
        dr.Close();
        SqlCommand cmt = new SqlCommand("UPDATE pmsParkingRecord SET parkExitTime='" + DateTime.Now.ToShortTimeString() + "'");
        cmt.Connection = conn;
        if (conn.State == System.Data.ConnectionState.Closed)
            conn.Open();
        SqlDataReader ds = cmt.ExecuteReader();
    }
    else
    {
        dr.Close();
        SqlCommand cmn = new SqlCommand("INSERT INTO pmsParkingRecord (parkUsername, parkFullName, parkAddress, parkVehicPlateNo, parkPaymentMethod, parkDate, parkEntryTime) VALUES ('" + lblUsername.Text + "', '" + lblFullName.Text + "', '" + lblAddress.Text + "', '" + txtPlateNo.Text + "', '" + lblPaymentMethod.Text + "', '" + Convert.ToDateTime(DateTime.Now.ToShortDateString()) + "', '" + Convert.ToDateTime(DateTime.Now.ToShortTimeString()) + "')");
        cmn.Connection = conn;
        if (conn.State == System.Data.ConnectionState.Closed)
            conn.Open();
        SqlDataReader ds = cmn.ExecuteReader();
    }
}
else
{
    lblWarning.Text = "License Plate No is not registered!";
}
dr.Close();

预期结果应该是将数据插入数据库并在标签上显示数据。

此行显示错误

SqlDataReader ds = cmn.ExecuteReader();

1 个答案:

答案 0 :(得分:3)

不要在查询文本中传递参数。而是使用SQLParameterCollection中的参数。

这里是一个例子,怎么做

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored 
    // in an xml column. 
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics.
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

来自SQLCommand.Parameters

优点是强大的类型以及SQL注入预防。