编程工具: VS2010;
数据库: Access2010;
数据库路径: strFilePath = @"C:\Users\huobaby\Desktop\huobaby.accdb";
数据库表名:strTabelName = "information";
表的结构:
编号 | 姓名 | 性别 | 年龄 |
1 | huobaby | 男 | 22 |
2 | Anni | 女 | 21 |
1.连接数据库, 并获取DataSet
/// <summary>
/// 连接数据库,并获取 DataSet
/// </summary>
/// <param name="strFilePath"> 数据库路径 </param>
/// <param name="strTabelName"> 数据库表名 </param>
/// <returns></returns>
private DataSet GetDataSet(string strFilePath, string strTabelName)
{
// 没有密码的连接方式
/* string strCon = @"Provider= Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + strFilePath + ";";
*/
// 有密码的连接方式
string strCon = @"Provider= Microsoft.ACE.OLEDB.12.0;" +
"Jet OLEDB:DataBase Password='huobaby60945'; "+ // 如果设置了用户名:User Id='huobaby';
" Data Source=" + strFilePath + ";";
DataSet ds = new DataSet();
try
{
OleDbConnection oleCon = new OleDbConnection(strCon);
oleCon.Open();
OleDbDataAdapter oleDap = new OleDbDataAdapter("select * from "+ strTabelName, oleCon);
oleDap.Fill(ds);
oleCon.Close();
oleCon.Dispose();
}
catch(Exception ex)
{
MessageBox.Show("数据库错误: " + ex.Message.ToString(), "提示",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return ds;
}
2. 获取DataTable, 并将数据填充到 dataGridView 中
// 获取 DataTabel
DataTable dt = GetDataSet(strFilePath, strTableName).Tables[0];
// 将DataTable的数据填充到 dataGridView 中
this.dataGridView1.DataSource = dt.DefaultView;
3.获取某行谋列数据
// 获取 DataTabel
DataTable dt = GetDataSet(strFilePath, strTableName).Tables[0];
MessageBox.Show(dt.Rows[0]["姓名"].ToString()); // 返回 huobaby
MessageBox.Show(dt.Rows[1][1].ToString()); // 返回 Anni
4. 修改、追加、删除记录
private void ChangeDataAccess(string strFilePath, string strTabelName)
{
// 没有密码的连接方式
/* string strCon = @"Provider= Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + strFilePath + ";";
*/
// 有密码的连接方式
string strCon = @"Provider= Microsoft.ACE.OLEDB.12.0;" +
"Jet OLEDB:DataBase Password='huobaby60945'; " + // 如果设置了用户名:User Id='huobaby';
" Data Source=" + strFilePath + ";";
try
{
OleDbConnection oleCon = new OleDbConnection(strCon);
oleCon.Open();
OleDbDataAdapter oleDap = new OleDbDataAdapter("select * from " + strTabelName, oleCon);
DataSet ds = new DataSet();
oleDap.Fill(ds);
OleDbCommandBuilder oleCb = new OleDbCommandBuilder(oleDap);
oleDap.UpdateCommand = oleCb.GetUpdateCommand();
DataTable dt = ds.Tables[0];
// 修改记录:将 "huobaby" 改为 "Baby"
dt.Rows[0]["姓名"] = "Baby";
oleDap.Update(dt);
// 追加一条记录行
DataRow dr = dt.NewRow();
dr["姓名"] = "";
dr["性别"] = "";
dr["年龄"] = "";
dt.Rows.Add(dt);
oleDap.Update(dt);
// 删除最第一条记录行
dt.Rows[0].Delete();
oleDap.Update(dt);
oleCon.Close();
oleCon.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("数据库错误: " + ex.Message.ToString(), "提示",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}