Use datatable to obtain the table's primary key

Source: Internet
Author: User
In many cases, we need to know what the table's primary key is. In ADO. net, datatable can be used to map tables in the database. So you can use the properties of the datatable Primarykey , It is Datacolumn [] Type is an array. We can use the following Code

Datacolumn [] Cols;
Cols = Table. primarykey;
// Note that not Cols is a datacolumn array, not a datacolumn variable. In this way, it is mainly used to deal with the problem of joint primary keys.
For ( Int I =   0 ; I < Cols. length; I ++ )
{
MessageBox. Show (Cols [I]. columnname );
}

This problem has been solved, but cols. length is 0. When the datatable is filled by default, no primary key information is obtained from the database. How to obtain the primary key? After research, we found that when filling dataset, we can use the missingschemaaction attribute of dataadapter to solve this problem, so we have the following code:

// Use dataadapter to fill the datatable
Dataadapter. missingschemaaction = Missingschemaaction. addwithkey;
Dataadapter. Fill (table );

Datacolumn [] Cols;
Cols = Table. primarykey;
// Note that not Cols is a datacolumn array, not a datacolumn variable. In this way, it is mainly used to deal with the problem of joint primary keys.
For ( Int I =   0 ; I < Cols. length; I ++ )
{
MessageBox. Show (Cols [I]. columnname );
}

in this way, we can get what we want. The missingschemaaction attribute is the operation to be performed when the existing dataset (or datatable) architecture does not match the imported data. Missingschemaaction. addwithkey is an enumeration value. It is used to add required columns and primary key information to complete the architecture. You can explicitly set primary key constraints on each able.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.