簡體   English   中英

將C#datetime值與SQL Server Compact 4 datetime進行比較

[英]Comparing C# datetime value to SQL Server Compact 4 datetime

我正在構建一個存儲一組日期時間的應用程序,以跟蹤打印特定報告的時間。 該報告由第二個表中也包含日期時間的信息組成。 我正在嘗試使報表填充僅在第一個表中最后一個日期時間之后的記錄的datagridview。

第一個表稱為“ deliverylog”,該表存儲了過去的打印日期。 第二個表稱為“ joblog”,它存儲先前作業條目的記錄。

當我運行該程序時,它運行良好,並在最后一個日期之后的所有記錄中填充了gridview,但未進行優化...僅在日期之后而不是時間中填充了日期。 我需要查詢以將gridview填充到第二個...。

DateTime lastDeliveryDate;

private void getLastDelivery() // Sets global variable lastDeliveryDate to the last timestamp entered in the deliverylog table 
{
    openLogConnection();

    try
    {
        command = new SqlCeCommand("SELECT TOP 1 * FROM deliverylog ORDER BY Id DESC", logConn);

        drLogSet = command.ExecuteReader();
        while (drLogSet.Read())
        {
            lastDeliveryDate = Convert.ToDateTime(drLogSet["Timestamp"]);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        logConn.Close();
    }
}

private void populateGridView()
{
    openLogConnection();

    try
    {
        command = new SqlCeCommand("SELECT * FROM joblog WHERE TimeStamp > @date", logConn);
        command.Parameters.AddWithValue("@date", lastDeliveryDate);

        dtLogSet = new DataTable();
        bsLogSet = new BindingSource();
        daLogSet = new SqlCeDataAdapter(command);
        cbLogSet = new SqlCeCommandBuilder(daLogSet);

        daLogSet.Fill(dtLogSet);
        bsLogSet.DataSource = dtLogSet;
        dataGridView1.DataSource = bsLogSet;

        dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        logConn.Close();
    }
}

任何人都知道如何使此工作正確嗎? 我將兩個表的時間戳都存儲為日期時間數據類型,並采用以下格式:“ MM / dd / yyyy hh:mm:ss tt”

我相信使用AddWithValue方法會在內部轉換值,並且可能會失去所需的時間精度。 而是使用Parameters集合的Add(String, SqlDbType)方法重載:

var dateParameter = command.Parameters.Add("@date", SqlDbType.DateTime);
dateParameter.Value = this.lastDeliveryDate;

通過使用調試器檢查變量來設置參數值之前,請確保您具有正確的值。

您可以嘗試使用DATEDIFF SQL函數而不是>運算符來確保正確的精度:

SELECT * FROM joblog WHERE DATEDIFF(second, @date, TimeStamp) > 0

問題可能是這條線:

lastDeliveryDate = Convert.ToDateTime(drLogSet["Timestamp"]);

假設您的TimeStamp字段是datetime類型,則應使用:

lastDeliveryDate = (DateTime) drLogSet["TimeStamp"];

請確認您的TimeStamp字段的數據類型。

您應該將日期格式設置為yyyyMMdd hh:mm:ss。

lastDeliveryDate.toString(“ yyyyMMdd hh:mm:ss”)。

在這篇文章中有更多詳細信息。 如何比較sqlite的TIMESTAMP值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM