C# 创建表ACCESS表,添加字段
C# 创建表ACCESS表,添加字段
//为了方便测试,数据库名字采用比较随机的名字,以防止添加不成功时还需要重新启动IIS来删除数据库。 //string dbName = "D:\\NewMDB" + DateTime.Now.Millisecond.ToString() + ".mdb"; ADOX.CatalogClass cat = new ADOX.CatalogClass(); ADODB.Connection cn = new ADODB.Connection(); //数据库文件不存在则创建 if (!File.Exists(DataPath)) { cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbName + ";"); } cn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbName, null, null, -1); cat.ActiveConnection = cn; //Response.Write("数据库:" + dbName + "已经创建成功!"); ADOX.TableClass tbl = new ADOX.TableClass(); tbl.ParentCatalog = cat; tbl.Name = "信息表"; //增加一个自动增长的字段 ADOX.ColumnClass col = new ADOX.ColumnClass(); col.ParentCatalog = cat; col.Type = ADOX.DataTypeEnum.adInteger; // 必须先设置字段类型 col.Name = "id"; col.Properties["Jet OLEDB:Allow Zero Length"].Value = false; col.Properties["AutoIncrement"].Value = true; tbl.Columns.Append(col, ADOX.DataTypeEnum.adInteger, 0); //增加一个文本字段 ADOX.ColumnClass col2 = new ADOX.ColumnClass(); col2.ParentCatalog = cat; col2.Name = "Description"; col2.Properties["Jet OLEDB:Allow Zero Length"].Value = false; tbl.Columns.Append(col2, ADOX.DataTypeEnum.adVarChar, 25); //增加数字字段 ADOX.ColumnClass col3 = new ADOX.ColumnClass(); col3.ParentCatalog = cat; col3.Name = "数字"; col3.Type = DataTypeEnum.adDouble; col3.Properties["Jet OLEDB:Allow Zero Length"].Value = false; tbl.Columns.Append(col3, ADOX.DataTypeEnum.adDouble, 666); //增加Ole字段 ADOX.ColumnClass col4 = new ADOX.ColumnClass(); col4.ParentCatalog = cat; col4.Name = "Ole类型"; col4.Type = DataTypeEnum.adLongVarBinary; col4.Properties["Jet OLEDB:Allow Zero Length"].Value = false; tbl.Columns.Append(col4, ADOX.DataTypeEnum.adLongVarBinary, 0); //设置主键 tbl.Keys.Append("PrimaryKey", ADOX.KeyTypeEnum.adKeyPrimary, "id", "", ""); cat.Tables.Append(tbl); //msg.Text = ("<br>数据库表:" + tbl.Name + "已经创建成功!"); System.Runtime.InteropServices.Marshal.ReleaseComObject(tbl); System.Runtime.InteropServices.Marshal.ReleaseComObject(cat); tbl = null; cat = null; cn.Close(); GC.WaitForPendingFinalizers(); GC.Collect();
本篇文章来源于 站长资讯网 原文链接:http://www.chinahtml.com/0612/aspnet-11664211899645.html

浙公网安备 33010602011771号