无需安装access用C#创建数据库,创建表
首先引用msadox.dll和msjro.dll(C:\Program Files\Common Files\System\ado\),msjro.dll可以从网上下载,然后引用
- using ADOX;
- using JRO;
- using System.IO;
然后编写相关函数
- /// <summary>
- /// 创建数据库
- /// </summary>
- /// <param name="mdbPath">路径</param>
- public void Create(string mdbPath)
- {
- if (File.Exists(mdbPath)) //检查数据库是否已存在
- {
- throw new Exception("目标数据库已存在,无法创建");
- }
- // 可以加上密码,这样创建后的数据库必须输入密码后才能打开
- mdbPath = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath;
- // 创建一个CatalogClass对象的实例,
- ADOX.CatalogClass cat = new ADOX.CatalogClass();
- // 使用CatalogClass对象的Create方法创建ACCESS数据库
- cat.Create(mdbPath);
- //创建数据库后关闭连接
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection);
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);
- }
- /// <summary>
- /// 连接数据库
- /// </summary>
- /// <param name="filename">文件名包含路径</param>
- /// <returns>返回连接字符串</returns>
- public ADODB.Connection Connection(string filename)
- {
- ADODB.Connection con = new ADODB.Connection();
- con.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+filename, null, null, -1);
- return con;
- }
- /// <summary>
- /// 创建数据表
- /// </summary>
- /// <param name="con">连接字符串</param>
- /// <param name="table_name">表的名称</param>
- /// <param name="column">字段</param>
- public void CreateTable(ADODB.Connection con,string table_name,params Column[] column)
- {
- CatalogClass cat = new CatalogClass();
- cat.ActiveConnection = con;
- Table table = new Table();
- Column col = new Column();
- col.ParentCatalog = cat;
- col.Type = DataTypeEnum.adInteger;
- col.Name = "ID";
- col.DefinedSize = 9;
- col.Properties["AutoIncrement"].Value = true;
- table.Columns.Append(col, DataTypeEnum.adInteger, 9);
- table.Keys.Append("FirstPrimaryKey",KeyTypeEnum.adKeyPrimary,col, null, null);
- table.Name = table_name;
- foreach (Column item in column)
- {
- table.Columns.Append(item);
- }
- cat.Tables.Append(table);
- //创建数据库后关闭连接
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat.ActiveConnection);
- System.Runtime.InteropServices.Marshal.FinalReleaseComObject(cat);
- }
示例:
- private void button1_Click(object sender, EventArgs e)
- {
- Create(Path.Combine(Application.StartupPath, "test.mdb"));
- Column col=new Column();
- col.Name="Name";
- col.Type=DataTypeEnum.adVarWChar;
- col.DefinedSize=50;
- CreateTable(Connection(Path.Combine(Application.StartupPath, "test.mdb")),"testtable", col);
- }