使用C#Data Reader检查Database字段是否为Nullable

时间:2014-06-20 14:19:44

标签: c# nullable

C#中是否有办法确定数据库字段是否可以以相对数据库/平台无关的方式为空?换句话说,在Oracle中我可以做这样的事情:

select column_name, nullable
from all_tab_columns
where table_name = :TABLE

但是这种方法与Oracle有关,我必须为其他平台提供一个等价物。

我希望通过数据提供商实现这一目标。我能够使用类似的东西提取数据类型:

AseCommand cmd = new AseCommand(sql, conn);
AseDataReader reader = cmd.ExecuteReader();

for (int i = 0; i < reader.FieldCount; i++)
{
    string name = reader.GetName(i);
    string dbTypeName = reader.GetDataTypeName(i);
    Type dbType = reader.GetFieldType(i);
}

在这个例子中它是Sybase,但这种方法在其他平台上是多态的,至少对于我一直在使用的数据库而言。

我唯一遗漏的是该字段是否可以为空。

1 个答案:

答案 0 :(得分:1)

C#中的OLEDB是一种非常与数据库无关的数据交互方式,它还支持检查空列。

    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\data.accdb;Persist Security Info=False;"; //This will be different for differing connection methods (you can find more on [ConnectionStrings.com][1]
    OleDbConnection conn = new OleDbConnection(connString);
    DataSet mainData = new DataSet();
    OleDbCommand accessCommand = new OleDbCommand("SELECT * FROM YOUR_TABLE_HERE", conn);
    OleDbDataAdapter dataAdapter = new OleDbDataAdapter(accessCommand); //create the SQL command
    conn.Open();
    dataAdapter.Fill(mainData, "YOUR_TABLE_HERE"); //fill the dataset with the data from our SQL
    DataTable dta = mainData.Tables[0];

    DataTable schema = conn.GetSchema();
    schema.Tables["YOUR_TABLE_HERE"].Columns["YOUR_COLUMN_HERE"].AllowDBNull; //gets or sets if the column allows nulls

    conn.close();

More info OLEDB from MS

GetSchema Docs