gpt4 book ai didi

c# - 如何检查 MS Access 数据库中是否存在指定的列?

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:50 25 4
gpt4 key购买 nike

我需要我的程序检查指定的列是否存在于 MS Access 2000 数据库中,如果不存在,则添加它。我使用 .NET Framework 2.0我尝试使用 oleDbConnection.GetSchema() 方法,但无法在元数据中找到列名称(我真的不是专业人士,呵呵)和 msdn 上的任何规范。如果有任何帮助,我将不胜感激。

感谢您的回答。这是我在代码中使用的解决方案:

bool flag = false; string[] restrictions = new string[] { null, null, mytable };
DataTable dtColumns = oleDbConnection1.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Columns, restrictions);
foreach (DataRow row in dtColumns.Rows)
{
if (mycolumnname==(string)row["COLUMN_NAME"]) flag = true;
}

最佳答案

这是我的 o/r-mapper 的一部分代码。你不能按原样使用它,因为它依赖于其他类,但我希望你能理解。

像这样定义限制

string[] restrictions = new string[] { null, null, tableName };

从表中检索列

private void RetrieveColumnInfo(OleDbConnection cnn, TableSchema tableSchema,
string[] restrictions, Func<string, string> prepareColumnNameForMapping)
{
using (DataTable dtColumns =
cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, restrictions)) {
string AutoNumberColumn = RetrieveAutoNumberColumn(cnn, tableSchema);
foreach (DataRow row in dtColumns.Rows) {
var col = new TableColumn();
col.ColumnName = (string)row["COLUMN_NAME"];
try {
col.ColumnNameForMapping =
prepareColumnNameForMapping(col.ColumnName);
} catch (Exception ex) {
throw new UnimatrixExecutionException(
"Error in delegate 'prepareColumnNameForMapping'", ex);
}
col.ColumnAllowsDBNull = (bool)row["IS_NULLABLE"];
col.ColumnIsIdentity = col.ColumnName == AutoNumberColumn;
DbColumnFlags flags = (DbColumnFlags)(long)row["COLUMN_FLAGS"];
col.ColumnIsReadOnly =
col.ColumnIsIdentity ||
(flags & (DbColumnFlags.Write | DbColumnFlags.WriteUnknown)) ==
DbColumnFlags.None;
if (row["CHARACTER_MAXIMUM_LENGTH"] != DBNull.Value) {
col.ColumnMaxLength = (int)(long)row["CHARACTER_MAXIMUM_LENGTH"];
}
col.ColumnDbType = GetColumnDbType((int)row["DATA_TYPE"]);
col.ColumnOrdinalPosition = (int)(long)row["ORDINAL_POSITION"];
GetColumnDefaultValue(row, col);

tableSchema.ColumnSchema.Add(col);
}
}
}

关于c# - 如何检查 MS Access 数据库中是否存在指定的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9435867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com