0
"SELECT SUM(Cost) FROM Repair WHERE RepairDate BETWEEN '" + startdate + "' AND '" + enddate + "'";

大家好,除了改成参数化查询外,这个sql有什么问题吗?当我尝试 ExecuteScalar 时,它给了我条件表达式错误中的数据类型不匹配:

public int TotalRepairCost(DateTime startdate, DateTime enddate)
{
        int total;
        OleDbConnection oleConn = new OleDbConnection(connString);

        oleConn.Open();

        string sql = "SELECT SUM(Cost) FROM Repair WHERE RepairDate BETWEEN '" + startdate + "' AND '" + enddate + "'";

        OleDbCommand cmd = new OleDbCommand(sql, oleConn);

        total = (int)cmd.ExecuteScalar();

        oleConn.Close();
        return total;
}

在我的 Windows 窗体按钮中单击

private void btnTotal_Click(object sender, EventArgs e)
{
        DateTime startdate = Convert.ToDateTime(txtStartDate.Text);
        DateTime enddate = Convert.ToDateTime(txtEndDate.Text);
        lblTotal.Text = client.TotalRepairCost(startdate, enddate).ToString();
}

在此处输入图像描述 在此处输入图像描述

在此处输入图像描述

4

1 回答 1

2

您应该使用命令参数 ( msdn ) 和decimal类型total

public decimal TotalRepairCost(DateTime startdate, DateTime enddate)
{
    decimal total;
    OleDbConnection oleConn = new OleDbConnection(connString);

    oleConn.Open();
    string sql = "SELECT SUM(Cost) FROM Repair WHERE RepairDate BETWEEN @StartDate AND @EndDate";

    OleDbCommand cmd = new OleDbCommand(sql, oleConn);
    cmd.Parameters.Add("@StartDate", OleDbType.Date);
    cmd.Parameters["@StartDate"].Value = startdate;

    cmd.Parameters.Add("@EndDate", OleDbType.Date);
    cmd.Parameters["@EndDate"].Value = enddate;

    total = (decimal)cmd.ExecuteScalar();

    oleConn.Close();
    return total;
}
于 2013-10-27T13:41:11.133 回答