基于C#Winform的Access数据库创建及备份

一、新建Access数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void NewDbBtn_Click(object sender, EventArgs e)
{
SaveFileDialog newfile = new SaveFileDialog();
newfile.Filter = "Microsoft Access数据库(*.mdb)|*.mdb";
if (newfile.ShowDialog() == DialogResult.OK)
{
string FileName = newfile.FileName;
string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName;
ADOX.Catalog catalog = new ADOX.Catalog();
try
{
catalog.Create(conn);
MessageBox.Show("创建成功!");
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
}

二、新建数据表

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
private void NewTbBtn_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
string FileName = openfile.FileName;
workspaceCON = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName;
}
//链接数据库
ADODB.Connection cn = new ADODB.Connection();
cn.Open(workspaceCON, null, null, -1);
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.ActiveConnection = cn;
//新建表
ADOX.Table table = new ADOX.Table();
CreateTbFrm createtbfrm = new CreateTbFrm();
DialogResult result = createtbfrm.ShowDialog();
if (result == DialogResult.OK)
{
table.Name = createtbfrm.tablename;
//新建列
ADOX.Column column = new ADOX.Column();
column.ParentCatalog = catalog;
//设置数据类型
column.Type = ADOX.DataTypeEnum.adInteger;
column.Name = "ID";
column.DefinedSize = 9;
column.Properties["AutoIncrement"].Value = true;
table.Columns.Append(column, ADOX.DataTypeEnum.adInteger, 0);
table.Keys.Append("FirstTablePrimaryKey", KeyTypeEnum.adKeyPrimary, "ID", null, null); //定义主键
catalog.Tables.Append(table);
cn.Close();
MessageBox.Show("创建成功!");
}
}
catch (Exception a)
{
MessageBox.Show(a.Message);
}
}

三、数据库备份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private void SaveAsBtn_Click(object sender, EventArgs e)
{
try
{
FileInfo file = new FileInfo(workspaceDB);
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.DefaultExt = "mdb";
saveFileDialog1.Title = "数据库文件备份";
saveFileDialog1.Filter = "Microsoft Access数据库(*.mdb)|*.mdb";
saveFileDialog1.OverwritePrompt = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
file.CopyTo(saveFileDialog1.FileName, true);
MessageBox.Show("数据库备份成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}

今日美言

When given the choice between being right or being kind, choose kind.

​ ——Mr Brown’s September Precet Precett