在C#中将记录插入Access 2000数据库

时间:2014-02-10 14:25:31

标签: c# sqlconnection

我需要使用C#在Access 2000数据库中插入记录。代码在SqlConnection上失败。请帮忙。

        string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Trading.mdb";
        string commandText = "INSERT INTO Order (OpenDate) VALUES (@OpenDate)";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(commandText, connection);
            command.Parameters.AddWithValue("@OpenDate", DateTime.Now);

            try
            {
                command.Connection.Open();
                int response = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: {0}" + ex.Message);
            }
        }            

2 个答案:

答案 0 :(得分:3)

问题:您正在使用MS-Access数据库,但使用的是SqlServer对象。

解决方案:您需要使用OleDbConnection对象而不是SqlConnectionOleDbCommand代替SqlCommand

试试这个:

    string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Trading.mdb";
    string commandText = "INSERT INTO Order (OpenDate) VALUES (?)";

    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        OleDbCommand command = new OleDbCommand(commandText, connection);
        command.Parameters.AddWithValue("@OpenDate", DateTime.Now);

        try
        {
            command.Connection.Open();
            int response = command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: {0}" + ex.Message);
        }
    }         

答案 1 :(得分:2)