Home All Groups Group Topic Archive Search About

Get the name of the primary key

Author
2 Apr 2005 4:03 AM
Patrick B
Working with a Microsoft Access database, what is the best way to get
the name of the primary key field? I know the table name.

Author
2 Apr 2005 5:23 AM
J L
You can use the datareader as follows:

Dim cn as New OleDbConnection(strConnectString)
Dim cmd as New OleDbCommand
Dim myReader as OleDbDataReader
Dim dt as DataTable
Dim dRow as DataRow
Dim strPrimaryKeyList as String

cn.Open()
cmd.Connection = cn
cmd.CommandText = "Select * From yourTable"
myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo)
dt = myReader.GetSchemaTable()
strPrimaryKeyList = ""
For Each dRow in dt.Rows
   If dRow("IsKey") then
      strPrimaryKeyList += dRow("ColumnName") & vbcrlf
   End If
Next
cn.Close()

When done strPrimaryKeyList holds a list of the primary key field
names.

Hope that helps,
John
(PS I typed this in adHoc so check for typos, but you should get the
idea)

On Fri, 01 Apr 2005 23:03:32 -0500, Patrick B <newsgr***@devzoo.com>
wrote:

Show quote
>Working with a Microsoft Access database, what is the best way to get
>the name of the primary key field? I know the table name.
Author
2 Apr 2005 5:48 AM
Patrick B
Excellent! Thanks. I was using ADOX and dealing with horrible bugs.

J L wrote:
Show quote
> You can use the datareader as follows:
>
> Dim cn as New OleDbConnection(strConnectString)
> Dim cmd as New OleDbCommand
> Dim myReader as OleDbDataReader
> Dim dt as DataTable
> Dim dRow as DataRow
> Dim strPrimaryKeyList as String
>
> cn.Open()
> cmd.Connection = cn
> cmd.CommandText = "Select * From yourTable"
> myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo)
> dt = myReader.GetSchemaTable()
> strPrimaryKeyList = ""
> For Each dRow in dt.Rows
>    If dRow("IsKey") then
>       strPrimaryKeyList += dRow("ColumnName") & vbcrlf
>    End If
> Next
> cn.Close()
>
> When done strPrimaryKeyList holds a list of the primary key field
> names.
>
> Hope that helps,
> John
> (PS I typed this in adHoc so check for typos, but you should get the
> idea)
>
> On Fri, 01 Apr 2005 23:03:32 -0500, Patrick B <newsgr***@devzoo.com>
> wrote:
>
>
>>Working with a Microsoft Access database, what is the best way to get
>>the name of the primary key field? I know the table name.
>
>

AddThis Social Bookmark Button