SQLDataReader

S

SQL

I'm new at this, so please forgive me if my question has a simple answer to
it.

I'm trying to get a value out of a SqlDataReader. Here is my code to do so:

Dim mySQLCommand As New SqlCommand("SELECT NextPrbKey FROM SystemAdmin", cn)
Dim mySQLReader As SqlDataReader = mySQLCommand.ExecuteReader()
intGetNextKey = mySQLReader.GetValue(0)

This does not return a value. I thought that GetValue(0) would return the
value of column 0 in my result set. What am I doing wrong?
Thanks.
 
K

Ken Tucker [MVP]

Hi,

Here is a simple datareader example.

Dim strConn As String

Dim conn As SqlConnection

Dim drCustomer As SqlDataReader

Dim cmd As SqlCommand

strConn = "Server = " + Environment.MachineName + "\VSdotNet;"

strConn += "Database = NorthWind;"

strConn += "Integrated Security = SSPI;"

conn = New SqlConnection(strConn)

cmd = New SqlCommand("Select Customers.*, (Customers.ContactTitle + ', ' +
Customers.ContactName) as FullName from Customers Order by ContactTitle,
ContactName", conn)

conn.Open()

drCustomer = cmd.ExecuteReader

Do While drCustomer.Read

ComboBox1.Items.Add(drCustomer("FullName"))

Loop

conn.Close()



Ken
 
W

William Ryan

You haven't moved the position.... Wrap the intGetNextKey line in between

While mySqlReader.Read
intGetNextKey = mySqlReader.GetString(0)
End While

One bit of caution...you may want to check for IsDbNull using something like
an IIF(IsDbNull(mySqlReader(0),string.Empty, mySqlReader.GetString(0))

b/c the way it works now, you'll throw an exception if you pull in a Null
value from the db. Of course, this won't be a problem if you're sure there
are no nulls, but it's worth mentioning nonetheless.

HTH,

Bill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top