对ACESS数据库操作时,删除完数据库后应对其数据库进行压缩,否则数据库容量会逐渐变大!!!!
private void button4_Click(object sender, System.EventArgs e)
{
OleDbConnection myConn = new OleDbConnection ( strCon ) ;
System.Data.OleDb.OleDbCommand myCommand =new OleDbCommand();
myCommand.Connection=myConn;
myConn.Open();
try
{
myCommand.CommandText="delete from gjb";
myCommand.ExecuteNonQuery();
//myCommand.CommandText="alter table gjb alter id counter(1,1)";//有了压缩数据库后,就不需要此句执行
//myCommand.ExecuteNonQuery();
myCommand.CommandText="delete from hz";
myCommand.ExecuteNonQuery();
//myCommand.CommandText="alter table hz alter id counter(1,1)";//有了压缩数据库后,就不需要此句执行
//myCommand.ExecuteNonQuery();
this.button1.Enabled=true;
this.button4.Enabled=false;
this.richTextBox1.Clear();
this.textBox1.Text="";
//MessageBox.Show("数据删除成功!");
}
catch (Exception ex)
{
MessageBox.Show("数据删除失败!"+ ex.ToString());
}
myCommand.Dispose();
myConn.Close();
myConn.Dispose();
if(myConn.State.ToString()=="Closed")
{
CompactAccessDB();
}
else
{
MessageBox.Show("数据库未关闭");
}
public static void CompactAccessDB()
{
try
{
//创建 Jet 引擎对象
object objJetEngine = Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine"));
//设置参数数组
//根据你所使用的Access版本修改 "Jet OLEDB:Engine Type=5" 中的数字.
//5 对应 JET4X 格式 (access 2000,2002)
object[] objParams = new object[] {
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "+Application.StartupPath+@"/gjfj.mdb", //输入连接字符串
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "+Application.StartupPath+@"/temp.mdb;Jet OLEDB:Engine Type=5" //输出连接字符串
};
//通过反射调用 CompactDatabase 方法
objJetEngine.GetType().InvokeMember("CompactDatabase",
System.Reflection.BindingFlags.InvokeMethod,
null,
objJetEngine,
objParams);
//删除原数据库文件
System.IO.File.Delete(Application.StartupPath+@"/gjfj.mdb");
//重命名压缩后的数据库文件
System.IO.File.Move(Application.StartupPath+@"/temp.mdb", Application.StartupPath+@"/gjfj.mdb");
//释放Com组件
System.Runtime.InteropServices.Marshal.ReleaseComObject(objJetEngine);
objJetEngine = null;
MessageBox.Show("数据删除并压缩成功!");
}
catch(Exception ex)
{
MessageBox.Show("数据库压缩中出现错误!"+ex.ToString());
}
一定要确保在数据库连接完全关闭后才能对其数据库进行压缩,否则不成功。