我在访问数据库中有一个名为“Streets”的表,我已经用
打开了一个连接OleDbConnection con = OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data source=" + mdbFileName);
我怎样才能到达我的桌旁?
答案 0 :(得分:3)
您需要'更改'表并使用ExecuteNonQuery。代码如下:
Dim dbName As String = "<path>\mdbFileName.mdb"
Dim tmpConString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbName & ";Persist Security Info=False"
Dim sqlText As String = ""
Using cn As New OleDbConnection(tmpConString)
cn.Open()
sqlText = "ALTER TABLE Table1 ADD COLUMN fldNew TEXT(50)"
Using cm As New OleDbCommand(sqlText, cn)
cm.ExecuteNonQuery()
End Using
End Using
这会在您的数据库中添加一个名为“fldNew”的新列。然后,您可以使用标准的UPDATE SQL命令将数据添加到新列中。
答案 1 :(得分:2)
将ADOX COM引用添加到项目中并尝试以下代码:
using ADOX;
//...
private void Test() {
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<path to your .mdb>";
CatalogClass cat = new CatalogClass();
cat.let_ActiveConnection(connString);
RenameField(cat, "YourTableName", "OriginalFieldName", "NewFieldName");
AddField(cat, "YourTableName", "YourNewFieldName", DataTypeEnum.adVarWChar, 50, "");
}
// Rename a field.
private void RenameField(CatalogClass cat, string tableName, string originalFieldName, string newFieldName) {
cat.Tables[tableName].Columns[originalFieldName].Name = newFieldName;
}
// Add a field to a specified table.
private void AddField(ADOX.CatalogClass cat, string tableName, string newFieldName, DataTypeEnum varType, int size, string defaultValue) {
ColumnClass col = new ColumnClass();
col.Name = newFieldName;
col.Type = varType;
col.DefinedSize = size;
col.Attributes = ColumnAttributesEnum.adColNullable;
cat.Tables[tableName].Columns.Append((object)col, DataTypeEnum.adInteger, 0);
if (!string.IsNullOrEmpty(defaultValue)) {
col.Properties["Default"].Value = defaultValue;
}
}
详细信息可以在以下博客文章中找到:
Rename Field in MS Access Programmatically using ADOX (C#.NET)
Add New Field in MS Access Programmatically using ADOX (C#.Net)
使用标准ADO.net将数据添加到新字段。