-1

我正在尝试使用两个日期从数据库中检索数据,但 Visual Studio 抛出语法错误。

以下是使用 sql 查询填充数据集的方法:

public DataSet OrderBetweenDates(string date1, string date2)
{


    //  string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Amrit\\Desktop\\Database.accdb ;Persist Security Info=False;";
    DataSet dataSet = new DataSet();
    OleDbConnection oleConn = new OleDbConnection(connString);

    try
    {
        oleConn.Open();
        string sql = "SELECT Order.OrderNumber, (Customer.Title +SPACE(2)+ Customer.CustomerName) as [Customer Name], Customer.CustomerEbayname, Customer.EmailAddress, Customer.PhoneNumber, (Customer.Address1 + SPACE(2) + Customer.Address2 + SPACE(2)+ Customer.City + SPACE(2) + Customer.PostCode + SPACE(2) + Customer.Country) as Address,  Order.ItemPurchased, Order.PurchasedDate, Order.TotalPrice FROM Customer INNER JOIN [Order] ON Customer.[CustomerID] = Order.[CustomerID] WHERE [PurchasedDate] >= #date1# AND [PurchasedDate] <= #date2#";
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
        dataAdapter.Fill(dataSet, "Customer");
    }
    catch (Exception ex)
    {
        MessageBox.Show("An exception has been occured\n" + ex.ToString());
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        oleConn.Close();
    }
    if (dataSet.Tables.Count <= 0)
        return null;
    else
        return dataSet;
}

在此处输入图像描述

4

3 回答 3

1

推荐的方式(强烈推荐)是使用参数。但是,如果您不想遵循最佳实践并且总是想陷入困境,请尝试以下操作:

string sql = @"SELECT [Order].OrderNumber,
(Customer.Title +SPACE(2)+ Customer.CustomerName) as [Customer Name],
Customer.CustomerEbayname, Customer.EmailAddress, Customer.PhoneNumber,
(Customer.Address1 + SPACE(2) + Customer.Address2 + SPACE(2)+ Customer.City
 + SPACE(2) + Customer.PostCode + SPACE(2) + Customer.Country) as Address,
[Order].ItemPurchased, Order.PurchasedDate, Order.TotalPrice
FROM Customer INNER JOIN [Order] ON Customer.[CustomerID] = Order.[CustomerID]
WHERE [PurchasedDate] >= #" + date1 + "# AND [PurchasedDate] <= #" + date2 + "#";

你注意到变化了吗?您的日期参数包含在查询字符串中。

于 2013-03-03T09:52:08.990 回答
0

你的情况如下:

WHERE [PurchasedDate] >= #date1# AND [PurchasedDate] <= #date2#

现在#date1#并且#date2#不是有效日期 - 您可能希望为这些查询添加参数。请参阅MD.Unicorn 在您的其他问题中给您的答案

于 2013-03-03T09:28:35.977 回答
0

除了已经提到的可能的日期格式问题;

SELECT Order.OrderNumber, 
...
Order.ItemPurchased, 
Order.PurchasedDate, 
Order.TotalPrice 
...

Order是 from 的关键字,ORDER BY并且需要 - 在所有地方 - 包含在[].

SELECT [Order].OrderNumber, 
...
于 2013-03-03T09:31:29.863 回答