C Access database add and delete simple method

  • 2020-05-30 20:58:23
  • OfStack

Reference set:
using System.Data.OleDb;


static string exePath = System.Environment.CurrentDirectory;// This procedure is located in the path 

// Create a connection object 
OleDbConnection conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=" + exePath + @"\ The file name .mdb"); 

1. For queries, OleDbDataAdapter is used to obtain table data (including the so-called "refresh" and "connect to the database") and query by conditions


private void  Fetch data table / The query ()
{
    conn.Open();
    // Fetch data table 
    //string sql = "select * from  The name of the table  order by  field 1";
    // The query 
    string sql = "select * from  The name of the table  where  field 2="...;

    OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); // Create the adapter object 
    DataTable dt = new DataTable(); // New table object 
    da.Fill(dt); // Populate the table object with the adapter object 
    dataGridView1.DataSource = dt; // Take the table object as DataGridView The data source 

    conn.Close();
}

Among them, "fetch data table" is a method that is frequently nested and called, so conn.Open and Close should be removed to avoid error reporting due to accumulation with Open in other methods.

2. OleDbCommand is used for modifying table data, such as adding, deleting and saving


private void  increase / delete / change ()
{
     conn.Open();
     // increase 
     string sql = "insert into  The name of the table ( field 1, field 2, field 3, field 4)values(...)";
     // delete  
     //string sql = "delete from  The name of the table  where  field 1="...; 
     // change  
     //string sql = "update student set  Student id =" ...; 

     OleDbCommand comm = new OleDbCommand(sql, conn);
     comm.ExecuteNonQuery(); 

     conn.Close();
}

The number of tuples in which ExecuteNonQuery has been successfully changed, so comm.ExecuteNonQuery () can also be modified to judge and prompt the user for success or failure.

int i = comm.ExecuteNonQuery();
if (i > 0)
{
      MessageBox.Show(" Data added successfully !", " Operating hints ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
      MessageBox.Show(" Add failure !", " Operating hints ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

3. Save the data changes in DataGridView


private void saveData2()
{
     dataGridView1.EndEdit();

     string sql = "select * from  The name of the table ";

     OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);

     OleDbCommandBuilder bld = new OleDbCommandBuilder(da);
     da.UpdateCommand = bld.GetUpdateCommand();

        // the DataGridView Assigned to dataTbale . (DataTable) "Is a type conversion, as long as what follows can be converted to dataTable type 
     DataTable dt = (DataTable)dataGridView1.DataSource; 

     da.Update(dt);
     dt.AcceptChanges();

     conn.Close(); 
}


Related articles: