C#对mdb文件进行增删改查操作
1.创建C#工程,工程名为MDBTest;
2.添加两个按钮,生成文件和添加数据;
3.创建数据库文件
添加引用,在“添加引用”对话框里切换到COM页面,选择“Microsoft ADO Ext. 2.8 for DDL and Security”,然后点击OK。在文件的开头using ADOX名字空间。然后添加如上面所示的代码就可以成功的创建Access 数据库了,代码如下:
/// <summary>
/// 创建Access数据库
/// </summary>
/// <param name="path">文件和文件路径</param>
/// <returns>真为创建成功,假为创建失败或是文件已存在</returns>
public bool CreateAccessDatabase(string path)
{
//创建ACCESS文件需要ADOX,创建引用,导入COM中的Microsoft ADO Ext. 2.8 for DLL and Security,并using ADOX;
FileInfo myfile = new FileInfo(path);
if (myfile.Exists)
{
//MessageBox.Show("当前文件夹下已存在文件,放弃创建");
return false;
}
else
{
try
{
ADOX.Catalog sldb = new ADOX.Catalog();
sldb.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + "Jet OLEDB:Engine Type=5");//创建sldb.mdb
sldb = null;
}
catch (Exception ex)
{
MessageBox.Show(Convert.ToString(ex.Message));
return false;
}
}
return true;
}
创建数据库之后需要建表,整个过程代码如下:
private void button_createfile_Click(object sender, EventArgs e)
{
string path = System.IO.Directory.GetCurrentDirectory();
path += "\\test.mdb";
if (!CreateAccessDatabase(path))
{
return;
}
//创建数据库文件成功后,开始建表
ArrayList columnames = new ArrayList();
columnames.Add("DTIME");
columnames.Add("NAME");
columnames.Add("AGE");
建表
CreateMDBTable(path, "SNTable", columnames);
/
}
4.通过sql语句往数据库中添加数据
string strSql = "";
OleDbConnection connet1 = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + path);
connet1.Open();
strSql = "insert into SNTable(DTIME,NAME,AGE) values ('" + strtime + "','" + "sfc" + "','" + "27" + "')";
OleDbCommand cmd = new OleDbCommand(strSql, connet1);
int a = cmd.ExecuteNonQuery();
connet1.Close();
5.查询和删除记录
this._fileName = strDBFilePath;
this._connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strDBFilePath + ";";
//1、建立连接 C#操作Access之读取mdb
this._odcConnection = new OleDbConnection(this._connectionString);
//2、打开连接 C#操作Access之读取mdb
this._odcConnection.Open();
///
//建立SQL查询
OleDbCommand odCommand = _odcConnection.CreateCommand();
//3、输入查询语句 C#操作Access之读取mdb
odCommand.CommandText = "select * from " + "SNTable";
//建立读取
OleDbDataReader odrReader = odCommand.ExecuteReader();
//查询并显示数据
int size = odrReader.FieldCount;
///
//删除重复的PCBASN
string strSqldpcbasn = "delete from SNTable where NAME ='" + "sfc" + "';";
OleDbCommand cmd1 = new OleDbCommand(strSqldpcbasn, _odcConnection);
int dnum = cmd1.ExecuteNonQuery();
if (dnum > 0)
{
MessageBox.Show("删除了"+dnum.ToString()+"条记录!!!");
//关闭连接 C#操作Access之读取mdb
odrReader.Close();
_odcConnection.Close();
return true;
}
else
{
MessageBox.Show("没有找到符合删除条件的记录!!!");
}
//关闭连接 C#操作Access之读取mdb
odrReader.Close();
_odcConnection.Close();
完整的示例工程工程源码获取地址:http://download.csdn.net/download/shufac/10024483