如何在c#中使用INSERT INTO进行访问数据库

时间:2017-03-06 14:40:24

标签: c# visual-studio-2015 command-line access

这是我的代码 请帮帮我

private void button1_Click(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|members list.mdb");
        OleDbCommand cmdoledb = new OleDbCommand();
        con.Open();
        OleDbCommand cmd = new OleDbCommand("INSERT INTO Members(name,family,age,Juncture scholarships) values('" + t1.Text + "','" + t2.Text + "','" + t3.Text + "','" + t4.Text + "')",con);
        cmd.ExecuteNonQuery();
        show();
        t1.Text = string.Empty;
        t2.Text = string.Empty;
        t3.Text = string.Empty;
        t4.Text = string.Empty;

    }
    private void show()
    {
        string d;
        OleDbConnection con;
        OleDbDataAdapter adap;
        DataSet ds = new DataSet();
        con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|members list.mdb");
        d = "select * from members";
        adap = new OleDbDataAdapter(d, con);
        adap.Fill(ds, "members");
        dataGridView1.DataSource = ds.Tables["members"];
    }

当我使用此代码时,我收到此错误

  

未处理的类型' System.Data.OleDb.OleDbException'   发生在System.Data.dll

中      

附加信息:INSERT INTO语句中的语法错误。

1 个答案:

答案 0 :(得分:2)

2件事:

使用参数

当字段名称包含空格时,使用括号

  OleDbCommand cmd = new OleDbCommand("INSERT INTO Members(name,family,age,[Juncture scholarships]) values(@name,@family,@age,@Js)",con);
    cmd.Parameters.AddWithValue("@name",t1.Text);
    cmd.Parameters.AddWithValue("@family",t2.Text);
    ...
    cmd.ExecuteNonQuery();
     ...