【轉載】C#對Access進行增刪改查

聲明:本文爲轉載,非原創,如有侵權,請告知,本人會盡快刪除。

原文地址:http://www.jb51.net/article/90780.htm


這篇文章整理了C#對Access數據庫的查詢、添加記錄、刪除記錄和更新數據等一系列的操作示例,有需要的可以參考學習。

首先是AccessHelper.cs,網上有下載,下面附送一份;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;
using System.Windows.Forms;
   
namespaceyxdain
{
  publicclassAccessHelper
  {
    privatestringconn_str = null;
    privateOleDbConnection ole_connection =null;
    privateOleDbCommand ole_command =null;
    privateOleDbDataReader ole_reader =null;
    privateDataTable dt =null;
   
    /// <summary>
    /// 構造函數
    /// </summary>
    publicAccessHelper()
    {
      //conn_str = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + Environment.CurrentDirectory + "\\yxdain.accdb'";
      conn_str =@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='"+ Environment.CurrentDirectory + "\\yxdain.accdb'";
         
      InitDB();
    }
   
    privatevoidInitDB()
    {
      ole_connection =newOleDbConnection(conn_str);//創建實例
      ole_command =newOleDbCommand();
    }
   
    /// <summary>
    /// 構造函數
    /// </summary>
    ///<param name="db_path">數據庫路徑
    publicAccessHelper(stringdb_path)
    {
      //conn_str ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+ db_path + "'";
      conn_str ="Provider=Microsoft.ACE.OLEDB.12.0;Data Source='"+ db_path +"'";
         
      InitDB();
    }
   
    /// <summary>
    /// 轉換數據格式
    /// </summary>
    ///<param name="reader">數據源
    /// <returns>數據列表</returns>
    privateDataTable ConvertOleDbReaderToDataTable(refOleDbDataReader reader)
    {
      DataTable dt_tmp =null;
      DataRow dr =null;
      intdata_column_count = 0;
      inti = 0;
   
      data_column_count = reader.FieldCount;
      dt_tmp = BuildAndInitDataTable(data_column_count);
   
      if(dt_tmp ==null)
      {
        returnnull;
      }
   
      while(reader.Read())
      {
        dr = dt_tmp.NewRow();
   
        for(i = 0; i < data_column_count; ++i)
        {
          dr[i] = reader[i];
        }
   
        dt_tmp.Rows.Add(dr);
      }
   
      returndt_tmp;
    }
   
    /// <summary>
    /// 創建並初始化數據列表
    /// </summary>
    ///<param name="Field_Count">列的個數
    /// <returns>數據列表</returns>
    privateDataTable BuildAndInitDataTable(intField_Count)
    {
      DataTable dt_tmp =null;
      DataColumn dc =null;
      inti = 0;
   
      if(Field_Count <= 0)
      {
        returnnull;
      }
   
      dt_tmp =newDataTable();
   
      for(i = 0; i < Field_Count; ++i)
      {
        dc =newDataColumn(i.ToString());
        dt_tmp.Columns.Add(dc);
      }
   
      returndt_tmp;
    }
   
    /// <summary>
    /// 從數據庫裏面獲取數據
    /// </summary>
    ///<param name="strSql">查詢語句
    /// <returns>數據列表</returns>
    publicDataTable GetDataTableFromDB(stringstrSql)
    {
      if(conn_str ==null)
      {
        returnnull;
      }
         
      try
      {
        ole_connection.Open();//打開連接
   
        if(ole_connection.State == ConnectionState.Closed)
        {
          returnnull;
        }
   
        ole_command.CommandText = strSql;
        ole_command.Connection = ole_connection;
   
        ole_reader = ole_command.ExecuteReader(CommandBehavior.Default);
   
        dt = ConvertOleDbReaderToDataTable(refole_reader);
   
        ole_reader.Close();
        ole_reader.Dispose();
      }
      catch(System.Exception e)
      {
        //Console.WriteLine(e.ToString());
        MessageBox.Show(e.Message);
      }
      finally
      {
        if(ole_connection.State != ConnectionState.Closed)
        {
          ole_connection.Close();
        }
      }
         
      returndt;
    }
   
    /// <summary>
    /// 執行sql語句
    /// </summary>
    ///<param name="strSql">sql語句
    /// <returns>返回結果</returns>
    publicintExcuteSql(stringstrSql)
    {
      intnResult = 0;
   
      try
      {
        ole_connection.Open();//打開數據庫連接
        if(ole_connection.State == ConnectionState.Closed)
        {
          returnnResult;
        }
   
        ole_command.Connection = ole_connection;
        ole_command.CommandText = strSql;
   
        nResult = ole_command.ExecuteNonQuery();
      }
      catch(System.Exception e)
      {
        //Console.WriteLine(e.ToString());
        MessageBox.Show(e.Message);
        returnnResult;
      }
      finally
      {
        if(ole_connection.State != ConnectionState.Closed)
        {
          ole_connection.Close();
        }
      }
   
      returnnResult;
    }
  }
}

定義變量,設置列標題;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
privateAccessHelper achelp;
......
  privatevoidForm1_Load(objectsender, EventArgs e)
  {
   
    achelp =newAccessHelper();
    stringsql1 ="select * from ycyx";
    databind1(sql1);
      
    dataGridView1.Columns[0].Visible =false;
    dataGridView1.Columns[1].HeaderCell.Value ="服務號碼";
    dataGridView1.Columns[2].HeaderCell.Value ="客戶名稱";
    dataGridView1.Columns[3].HeaderCell.Value ="歸屬地區";
    dataGridView1.Columns[4].HeaderCell.Value ="當前品牌";
    dataGridView1.Columns[5].HeaderCell.Value ="當前套餐";
    dataGridView1.Columns[6].HeaderCell.Value ="當前狀態";
  }

顯示數據表全部內容;

1
2
3
4
5
6
privatevoiddatabind1(stringsqlstr)
{
  DataTable dt =newDataTable();
  dt = achelp.GetDataTableFromDB(sqlstr);
  dataGridView1.DataSource = dt;
}

讀取要更新記錄到更新窗體控件;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
privatevoidbutton3_Click(objectsender, EventArgs e)
{
  if(dataGridView1.SelectedRows.Count < 1 || dataGridView1.SelectedRows[0].Cells[1].Value ==null)
  {
    MessageBox.Show("沒有選中行。","M營銷");
    return;
  }
  //f3.Owner = this;
  DataTable dt =newDataTable();
  objectoid = dataGridView1.SelectedRows[0].Cells[0].Value;
  stringsql ="select * from ycyx where ID="+ oid;
  dt = achelp.GetDataTableFromDB(sql);
  f3 =newForm3();
  f3.id =int.Parse(oid.ToString());
  //f3.id = 2;
  f3.Text1 = dt.Rows[0][1].ToString();
  f3.Text2 = dt.Rows[0][2].ToString();
  f3.Text3 = dt.Rows[0][3].ToString();
  f3.Text4 = dt.Rows[0][4].ToString();
  f3.Text5 = dt.Rows[0][5].ToString();
  f3.Text6 = dt.Rows[0][6].ToString();
   
  f3.ShowDialog();
     
}

添加記錄;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
privatevoidbutton4_Click(objectsender, EventArgs e)
{
  if(textBox1.Text ==""&& textBox2.Text ==""&& textBox3.Text ==""&& textBox4.Text ==""&& textBox5.Text ==""&& textBox6.Text =="")
  {
    MessageBox.Show("沒有要添加的內容","M營銷添加");
    return;
  }
  else
  {
    stringsql ="insert into ycyx (fwhm,khmc,gsdq,dqpp,dqtc,dqzt) values ('"+ textBox1.Text +"','"+ textBox2.Text +"','"+
      textBox3.Text +"','"+ textBox4.Text +"','"+ textBox5.Text +"','"+ textBox6.Text +"')";
    intret = achelp.ExcuteSql(sql);
    stringsql1 ="select * from ycyx";
    databind1(sql1);
    textBox1.Text ="";
    textBox2.Text ="";
    textBox3.Text ="";
    textBox4.Text ="";
    textBox5.Text ="";
    textBox6.Text ="";
  }
}

刪除記錄;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
privatevoidbutton2_Click(objectsender, EventArgs e)
{
  if(dataGridView1.SelectedRows.Count < 1 || dataGridView1.SelectedRows[0].Cells[1].Value ==null)
  {
    MessageBox.Show("沒有選中行。","M營銷");
  }
  else
  {
    objectoid = dataGridView1.SelectedRows[0].Cells[0].Value;
    if(DialogResult.No == MessageBox.Show("將刪除第 "+ (dataGridView1.CurrentCell.RowIndex + 1).ToString() +" 行,確定?","M營銷", MessageBoxButtons.YesNo))
    {
      return;
    }
    else
    {
      stringsql ="delete from ycyx where ID="+ oid;
      intret = achelp.ExcuteSql(sql);
    }
    stringsql1 ="select * from ycyx";
    databind1(sql1);
  }
}

查詢;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
privatevoidbutton13_Click(objectsender, EventArgs e)
{
  if(textBox23.Text =="")
  {
    MessageBox.Show("請輸入要查詢的當前品牌","M營銷");
    return;
  }
  else
  {
    stringsql ="select * from ycyx where dqpp='"+ textBox23.Text +"'";
    DataTable dt =newSystem.Data.DataTable();
    dt = achelp.GetDataTableFromDB(sql);
    dataGridView1.DataSource = dt;
  }
}

用戶確定顯示或不顯示哪些數據列;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
privatevoidbutton15_Click(objectsender, EventArgs e)
{
  if(checkBox1.Checked ==true)
  {
    dataGridView1.Columns[1].Visible =true;
  }
  else
  {
    dataGridView1.Columns[1].Visible =false;
  }
   
  if(checkBox2.Checked ==true)
  {
    dataGridView1.Columns[2].Visible =true;
  }
  else
  {
    dataGridView1.Columns[2].Visible =false;
  }
   
  if(checkBox3.Checked ==true)
  {
    dataGridView1.Columns[3].Visible =true;
  }
  else
  {
    dataGridView1.Columns[3].Visible =false;
  }
   
  if(checkBox4.Checked ==true)
  {
    dataGridView1.Columns[4].Visible =true;
  }
  else
  {
    dataGridView1.Columns[4].Visible =false;
  }
   
  if(checkBox5.Checked ==true)
  {
    dataGridView1.Columns[5].Visible =true;
  }
  else
  {
    dataGridView1.Columns[5].Visible =false;
  }
   
  if(checkBox6.Checked ==true)
  {
    dataGridView1.Columns[6].Visible =true;
  }
  else
  {
    dataGridView1.Columns[6].Visible =false;
  }
}

更新數據;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
  publicpartialclassForm3 : Form
  {
    privateAccessHelper achelp;
    privateintiid;
   
    publicForm3()
    {
      InitializeComponent();
      achelp =newAccessHelper();
      iid = 0;
    }
   
    // 更新
    privatevoidbutton1_Click(objectsender, EventArgs e)
    {
      try
      {
        //UPDATE Person SET Address = 'Zhongshan 23', City = 'Nanjing'WHERE LastName = 'Wilson'
        stringsql ="update ycyx set fwhm='"+textBox1.Text+"',khmc='"+textBox2.Text+"',gsdq='"+textBox3.Text+"',dqpp='"+textBox4.Text+
          "',dqtc='"+textBox5.Text+"',dqzt='"+textBox6.Text+"' where ID="+iid;
             
   
        intret = achelp.ExcuteSql(sql);
        if(ret > -1)
        {
          this.Hide();
          MessageBox.Show("更新成功","M營銷");
        }
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
   
         
   
    }
   
    privatevoidForm3_Load(objectsender, EventArgs e)
    {
   
    }
   
    publicintid
    {
      get{return this.iid; }
      set{this.iid = value; }
    }
   
   
    publicstringText1
    {
      get{return this.textBox1.Text; }
      set{this.textBox1.Text = value; }
    }
   
    publicstringText2
    {
      get{return this.textBox2.Text; }
      set{this.textBox2.Text = value; }
    }
   
    publicstringText3
    {
      get{return this.textBox3.Text; }
      set{this.textBox3.Text = value; }
    }
   
    publicstringText4
    {
      get{return this.textBox4.Text; }
      set{this.textBox4.Text = value; }
    }
   
    publicstringText5
    {
      get{return this.textBox5.Text; }
      set{this.textBox5.Text = value; }
    }
   
    publicstringText6
    {
      get{return this.textBox6.Text; }
      set{this.textBox6.Text = value; }
    }
   
    //取消
    privatevoidbutton2_Click(objectsender, EventArgs e)
    {
      this.Hide();
    }
  }
}

注意此處有一個技巧;C# Winform,在窗體之間傳值,或在一個窗體中設置另一個窗體的控件的值時,有多種方式;最好方式是如上代碼所示;使用.net的getset屬性; 

控件是一個窗體的私有變量,不能在另一個窗體中直接訪問;爲了在a窗體中設置b窗體的控件的值,對b窗體的控件都添加一個帶getset的公共屬性,就可在a中設置b中控件的值,具體看代碼;

以上就是C#對Access進行增刪改查的完整示例代碼,希望對大家學習C#能有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章