您的位置:首页 > 数据库

C#动态创建数据库

2013-04-10 15:15 316 查看
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using ADOX;

namespace WfpApp

{

/// <summary>

/// 创建库需要添加COM引用:Microsoft ADO Ext. 2.8 for DDL and Security

/// 创建数据表需要添加COM引用:Microsoft ActiveX Data Objects 2.8 Library

/// </summary>

public class DynamicAccess

{

public DynamicAccess(string local)

{

_DbPath = local;

}

private string _DbPath;

/// <summary>

/// ACCESS数据库路径,包含文件名称

/// </summary>

public string DbPath

{

get { return _DbPath; }

set { _DbPath = value; }

}

private string _strErrorInfo;

/// <summary>

/// 获取异常信息

/// </summary>

/// <returns></returns>

public string GetStrErrorInfo()

{

return _strErrorInfo;

}

/// <summary>

/// 动态创建ACCESS

/// </summary>

/// <returns></returns>

public bool CreateAccess()

{

try

{

ADOX.Catalog catalog = new ADOX.Catalog();

catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DbPath + ";Jet OLEDB:Engine Type=5");

return true;

}

catch (Exception ex)

{

_strErrorInfo = ex.Message;

return false;

}

}

public bool CreateTable()

{

try

{

ADOX.Catalog catalog = new ADOX.Catalog();

//创建链接

ADODB.Connection cn = new ADODB.Connection();

//打开

cn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DbPath, null, null, -1);

//激活链接

catalog.ActiveConnection = cn;

//创建表

ADOX.Table table = new ADOX.Table();

table.Name = "FirstTable";

//创建列

ADOX.Column column = new ADOX.Column();

column.ParentCatalog = catalog;

//列名称

column.Name = "RecordId";

//列类型

column.Type = DataTypeEnum.adInteger;

//默认长度

column.DefinedSize = 9;

//自动增长列

column.Properties["AutoIncrement"].Value = true;

//将列添加到表中

table.Columns.Append(column, DataTypeEnum.adInteger, 9);

//第一列为主键

table.Keys.Append("FirstTablePrimaryKey", KeyTypeEnum.adKeyPrimary, column, null, null);

table.Columns.Append("CustomerName", DataTypeEnum.adVarWChar, 50);

table.Columns.Append("Age", DataTypeEnum.adInteger, 9);

table.Columns.Append("Birthday", DataTypeEnum.adDate, 0);

catalog.Tables.Append(table);

cn.Close();

return true;

}

catch (Exception ex)

{

_strErrorInfo = ex.Message;

return false;

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: