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.

Re: Get the name of the primary key by J

J
Fri Apr 01 23:23:59 CST 2005

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 <newsgroup@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.


Re: Get the name of the primary key by Patrick

Patrick
Fri Apr 01 23:48:36 CST 2005

Excellent! Thanks. I was using ADOX and dealing with horrible bugs.

J L wrote:
> 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 <newsgroup@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.
>
>