在Access中添加记录但我怎样才能确定是否添加了记录C#?

时间:2010-09-16 22:02:44

标签: c# ms-access

我正在做一个项目,我想在C#上使用Windows窗体应用程序向accdb(Access数据库)添加一条记录我已经得到了似乎有效的代码,即它没有显示任何错误并且似乎运行但是它不添加记录,我怎么能确定添加此记录(图像)?任何想法,代码,帮助将不胜感激

这是我的代码

enter code here

    private void button4_Click(object sender, EventArgs e)
    {

        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Title = "Abrir escudo de municipio";

        //openFileDialog1.Filter ="IMG Files|*.jpg|JPG Files|*.png|PNG Files|*.bmp Files|BMP Files|";
        openFileDialog1.Filter = "JPEG Images|*.jpg|GIF Images|*.gif|BITMAPS|*.bmp";
        openFileDialog1.InitialDirectory = @"C:\";


        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {

            // textBox1.Show(openFileDialog1.FileName.ToString());

            //MessageBox.Show(openFileDialog1.FileName.ToString());
            textBox1.Text = openFileDialog1.FileName.ToString();



            String filename = openFileDialog1.FileName.ToString();
            byte[] buffer = File.ReadAllBytes(filename);


            using (var conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Policias.accdb"))

            using (var cmd = conn.CreateCommand())
            {

                cmd.CommandText = "INSERT INTO DetallesMunicipio(imagen) VALUES (@imagen)";
                cmd.Parameters.AddWithValue("@imagen", buffer);
                conn.Open();
                cmd.ExecuteNonQuery();



            }
        }
        else
        {
            MessageBox.Show("Please select an image");

        }

    }

2 个答案:

答案 0 :(得分:0)

验证cmd.ExecuteNonQuery()的返回值。

ExecuteNonQuery将返回受影响的行数,在您的情况下,数字记录为INSERTed。

MSDN文档: OleDbCommand.ExecuteNonQuery Method

在您插入记录的块中,根据您希望插入的记录数检查对ExecuteNonQuery()的调用的返回值:

// ...
using (var cmd = conn.CreateCommand()) { 
    cmd.CommandText = "INSERT INTO DetallesMunicipio(imagen) VALUES (@imagen)"; 
    cmd.Parameters.AddWithValue("@imagen", buffer); 
    conn.Open(); 
    int recordsInserted = cmd.ExecuteNonQuery(); 
    if (recordsInserted != 1) {  // if you expect to insert 1 record.
        // Do something because the INSERT failed.
    }
} 
// ...

如果您发现此返回值为0,那么您的INSERT不起作用,但这并不意味着存在错误。如果有错误,则抛出异常。

答案 1 :(得分:0)

您的参数传递错误了吗?如果您尝试这段代码会发生什么:

cmd.CommandText = "INSERT INTO DetallesMunicipio(imagen) VALUES (@imagen)";
OleDbParameter imageParameter = cmd.Parameters.Add("@imagen", OleDbType.Binary);
imageParameter.Value = buffer;
imageParameter.Size = buffer.Length;
conn.Open();
cmd.ExecuteNonQuery();