且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从表单C#将数据插入到Access数据库

更新时间:2023-01-29 08:51:26

密码是一个保留字。支架该字段名称,以避免混淆数据库引擎。

 插入到登录(用户名,[密码])


I started learning about C# and have become stuck with inserting information from textboxes into an Access database when a click button is used.

The problem I get is during the adding process. The code executes the Try... Catch part and then returns an error saying "Microsoft Access Database Engine" and doesn't give any clues.

Here is the code:

namespace WindowsFormsApplication1
{
    public partial class FormNewUser : Form
    {
        public FormNewUser()
        {
            InitializeComponent();
        }

        private void BTNSave_Click(object sender, EventArgs e)
        {
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Copy Cegees\Cegees\Cegees\Login.accdb";

            String Username = TEXTNewUser.Text;
            String Password = TEXTNewPass.Text;

            OleDbCommand cmd = new OleDbCommand("INSERT into Login (Username, Password) Values(@Username, @Password)");
            cmd.Connection = conn;

            conn.Open();

            if (conn.State == ConnectionState.Open)
            {
                cmd.Parameters.Add("@Username", OleDbType.VarChar).Value = Username;
                cmd.Parameters.Add("@Password", OleDbType.VarChar).Value = Password;

                try
                {
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Data Added");
                    conn.Close();
                }
                catch (OleDbException ex)
                {
                    MessageBox.Show(ex.Source);
                    conn.Close();
                }
            }
            else
            {
                MessageBox.Show("Connection Failed");
            }
        }
    }
}

Password is a reserved word. Bracket that field name to avoid confusing the db engine.

INSERT into Login (Username, [Password])