我正在尝试创建一个由两个表组成的Access数据库。我在以下方法中的第88行上收到System.Runtime.InteropServices.COMException。当我尝试将表追加到Catalog对象时发生异常。有人可以解释出什么问题以及如何解决吗?
public bool CreateNewAccessDatabase(string fileName)
{
bool result = false;
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table provTable = new ADOX.Table();
ADOX.Key provKey = new ADOX.Key();
ADOX.Table locTable = new ADOX.Table();
ADOX.Key locKey = new ADOX.Key();
ADOX.Column provCol = new Column();
ADOX.Column locCol = new Column();
//Create the Province table and it's fields.
provTable.Name = "Provinces";
provCol.Name = "id";
provCol.Type = ADOX.DataTypeEnum.adInteger;
provTable.Columns.Append(provCol);
provTable.Columns.Append("name", ADOX.DataTypeEnum.adVarWChar, 4);
provKey.Name = "Primary Key";
provKey.Columns.Append("id");
provKey.Type = KeyTypeEnum.adKeyPrimary;
//Create the Locations table and it's fields
locTable.Name = "Locations";
locCol.Name = "id";
locCol.Type = ADOX.DataTypeEnum.adInteger;
locTable.Columns.Append(locCol);
locTable.Columns.Append("name", ADOX.DataTypeEnum.adVarWChar, 50);
locTable.Columns.Append("price", ADOX.DataTypeEnum.adVarWChar, 8);
locKey.Name = "Primary Key";
locKey.Columns.Append("id");
locKey.Type = KeyTypeEnum.adKeyPrimary;
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + "; Jet OLEDB:Engine Type=5");
// Must create database file before applying autonumber to column
provCol.ParentCatalog = cat;
provCol.Properties["AutoIncrement"].Value = true;
locCol.ParentCatalog = cat;
locCol.Properties["AutoIncrement"].Value = true;
cat.Tables.Append(provTable); // <<< Exception triggered here
cat.Tables.Append(locTable);
//Now Close the database
ADODB.Connection con = cat.ActiveConnection as ADODB.Connection;
if (con != null)
con.Close();
result = true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.StackTrace);
result = false;
}
cat = null;
return result;
}
最佳答案
您将文本字段声明为ADOX.DataTypeEnum.adVarChar
,但是所有Access Text
字段都能够存储Unicode,因此您需要将它们声明为ADOX.DataTypeEnum.adVarWChar
。
关于c# - 用ADOX创建Access数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27865009/