如何使用c#在访问数据库中进行时间戳

时间:2014-01-22 19:33:46

标签: c# ms-access

private void button1_Click(object sender, EventArgs e)
{
    OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString =@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1.accdb";
    OleDbCommand command = new OleDbCommand();
    command.CommandText = "INSERT INTO Table1 (Emp_ID,Asset_ID)VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";
    mycon.Open();
    command.Connection = mycon;
    command.ExecuteNonQuery();
    mycon.Close();
}

这是我编写的代码,用于在访问数据库中插入一些细节。我希望这个按钮单击还可以将点击的日期和时间添加到我的数据库中的列中。我试图直接在INSERT中添加一个函数Ge​​tDate,但它无法执行。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

我还没有测试过这段代码,但它应该让你开始......

private void button1_Click(object sender, EventArgs e)
{
    using OleDbConnection mycon = new OleDbConnection()
    {
        mycon.ConnectionString =@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1.accdb";

        OleDbCommand command = new OleDbCommand();
        command.CommandText = "INSERT INTO Table1 (Emp_ID, Asset_ID, Date_Column) VALUES (?, ?, ?)";

        command.Parameters.Add("@EmpID", OleDbType.VarChar, 80).Value = textBox1.Text;
        command.Parameters.Add("@AssetID", OleDbType.VarChar, 80).Value = textBox2.Text;
        command.Parameters.Add("@Timestamp", OleDbType.Date).Value = DateTime.Now;

        command.Connection = mycon;
        mycon.Open();
        command.ExecuteNonQuery();
    }
}

答案 1 :(得分:0)

添加默认值为now

的datetime列

可以像下面这样做

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn