使用c#,net将数据插入到访问中

时间:2014-01-23 06:07:21

标签: c# ms-access

下面是附加代码,代码工作正常,但它没有将值插入到我创建的访问数据库表中,两个代码都没有显示任何错误

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

            private void textBox2_TextChanged(object sender, EventArgs e)
            {
            }

            private void submit_Click(object sender, EventArgs e)                
            {      
                OleDbConnection cnon = new OleDbConnection();
                cnon.ConnectionString =@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\visual_c\Database71.accdb";
                OleDbCommand command = new OleDbCommand();
                command.CommandText = "INSERT INTO electricity (Asset_name,Asset_number)VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";
                cnon.Open();
                command.Connection = cnon;
                command.ExecuteNonQuery();
                cnon.Close();
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

你在这里错过了一个空格:

"(Asset_name,Asset_number)VALUES"

尝试更改命令字符串:

command.CommandText = "INSERT INTO electricity (Asset_name,Asset_number) VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";

您应该使用parameterized queries来阻止Sql Injection攻击

command.CommandText = "INSERT INTO electricity (Asset_name,Asset_number) VALUES(@name,@number)";
command.Parameters.AddWithValue("@name", textBox1.Text);
command.Parameters.AddWithValue("@number", textBox2.Text);

答案 1 :(得分:0)

使用参数化查询 确保您的按钮OnClick事件

command.CommandText = "INSERT INTO electricity (Asset_name,Asset_number) VALUES (@Assetname,@Assetnumber)",cnon;

command.Parameters.AddWithValue("@Assetname", textBox1.Text);
command.Parameters.AddWithValue("@Assetnumber", textBox2.Text);