oledb 访问ACCESS

来源:互联网 发布:深孔爆破的爆破网络 编辑:程序博客网 时间:2024/05/15 21:38

我擦!!!终于搞定,用了大半天

在第一次用access的时候
1,排除了 access表不能插入
2,排除了是语法上的错误
3,检验 是写的SQL语句有问题

4,也排除了是数据库关键字的问题

5,注:填入的数据与数据库的数据的类型的必须一致

6. 必须得加“[ ]” ? string insertSQL = "INSERT INTO ProductDB" + " ([Product],[Price],[Number]) " + "VALUES (?,?,?)";       有些是关键字,所以得加“[ ]”。


   private void btnConfirm_Click(object sender, EventArgs e)
        {
            //建立数据库连接
            using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=D:\Personal\Desktop\Database6.mdb"))
            {


                try
                {
                   /*
                    //操作数据库
                 


                    // The insertSQL string contains a SQL statement that 
                    // inserts a new row in the source table.
                    string insertSQL = "INSERT INTO ProductDB" + " ([Product],[Price],[Number]) " + "VALUES (?,?,?)";
                    OleDbCommand cmd= new OleDbCommand(insertSQL);
                    cmd.Parameters.Add("@Product", OleDbType.VarWChar, 30).Value = txtName.Text;
                    cmd.Parameters.Add("@Price", OleDbType.VarWChar, 30).Value = txtPrice.Text;
                    cmd.Parameters.Add("@Number", OleDbType.VarWChar, 30).Value = txtNum.Text;
                    // Set the Connection to the new OleDbConnection.
                    cmd.Connection = conn;


                    // Open the connection and execute the insert command. 
                    try
                    {
                        conn.Open();
                       int i= cmd.ExecuteNonQuery();
                        if(i>0)
                        {
                            MessageBox.Show("添加失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    // The connection is automatically closed when the 
                    // code exits the using block.


                }
                catch (Exception EX)
                {
                    MessageBox.Show("添加失败" + EX.ToString());
                }
                finally
                {
                    //关闭数据库
                    conn.Close();
                }


            }
        }
    }

0 0
原创粉丝点击