0

在单击保存按钮数据插入 dataGridView 并显示后,我有此代码用于将数据插入 access 2013

当停止程序并重新启动时,数据未存储在数据库中。我做了很多搜索,但找不到解决方案。我的课程代码和我的按钮保存代码

class DB
{
    public static OleDbConnection con = new OleDbConnection();
    static DB()
    {
        con.ConnectionString = "Provider=MICROSOFT.ACE.OLEDB.12.0; " +
                "Data Source=|DataDirectory|//Phonebook-db.accdb;Persist Security Info=True";
    }
    public static void Insert(Person p1)
    {
        try
        {
            OleDbCommand cmd = con.CreateCommand();
            con.Open();
            string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES('" + p1.Name + "','" + p1.Family + "','" + p1.Telephone + "','" + p1.Major + "')";
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = s;
            cmd.ExecuteNonQuery();
            con.Close();
            System.Windows.Forms.MessageBox.Show("Record successfully Added");
        }
        catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }
    }

}

        Person p = new Person();
        p.Name = txtname.Text;
        p.Family = txtfamily.Text;
        p.Telephone = txttell.Text;
        p.Major = txtmajor.Text;
        DB.Insert(p);
        txttell.Text = "";
        txtmajor.Text = "";
        txtname.Text = "";
        txtfamily.Text = "";
        List<Person> people = DB.GetPeople();
        dataGridView1.DataSource = people;
4

1 回答 1

1

选择项目文件中列出的 ACCDB 文件,选择Copy To Output Directory并将其值设置为Never(并记住 |DataDirectory| 是指向(对于 ASP.NET 项目)到 APP_DATA 的替换字符串,您的记录被插入到复制到该目录中的数据库中.

说请考虑使用参数化查询创建sql命令,而不是字符串连接

   try
   {
        OleDbCommand cmd = con.CreateCommand();
        con.Open();
        string s = "INSERT INTO Industrialist (S_Name,S_Family,S_Telephone,S_Major)VALUES(" +
                   "?,?,?,?)";
        cmd.CommandText = s;
        cmd.Parameters.AddWithValue("@p1",p.Name);
        cmd.Parameters.AddWithValue("@p2",p.Family);
        cmd.Parameters.AddWithValue("@p3",p.Telephone);
        cmd.Parameters.AddWithValue("@p4",p.Major);
        cmd.ExecuteNonQuery();
        con.Close();
        System.Windows.Forms.MessageBox.Show("Record successfully Added");
    }
    catch (OleDbException exp) { MessageBox.Show(exp.ToString()); }

当然在执行命令之前不要关闭连接。

另一个需要改变的地方是连接的使用模式。不要创建全局连接并在应用程序的整个生命周期内保留它。只需在需要时创建和使用它,然后立即关闭/处置

using(OleDbConnection con = new OleDbConnection("Provider=MICROSOFT.ACE.OLEDB.12.0; " +
                      "Data Source=|DataDirectory|//Phonebook-db.accdb;" + 
                      "Persist Security Info=True"))
{
   try
   {
        OleDbCommand cmd = con.CreateCommand();
        ....
   }
} // <- Here at the closing brace the connectio will be close and disposed 
于 2013-06-03T13:32:38.473 回答