VB ODBC Connection problems

Harlequin

Member
Joined
Dec 20, 2008
Messages
6
Programming Experience
Beginner
I created a small database called bank. This has a table called 'person' and this contains a field called 'fname'.
I'm trying to write a console project to connect to the database, read the field and display the two records.
I have a dsn file in c:\xxx\xxx\xxx. This is called myODBC. When I tested the connection I get a connection was successful message.
I've tried putting the full address for the dsn file but it makes no difference.
I copied the following from the book 'Beginning VB 2008 Databases".
The code executes to the 'Dim cmd As New OdbcCommand(sql, conn)" and it crashes to the Close reader and displays the error message.

All help would be appreciated as I'm getting more and more frustrated and more and more confused as to where I'm going wrong. Please explain as simply as possible as I fear my ability to comprehend has been seriously impaired.



Imports System
Imports System.Data
Imports System.Data.Odbc

Module mySQLtest
Sub Main()
' set up connection string
Dim connString As String = ("myODBC")

'set up query string
Dim sql As String = "select fname from people"

' Declare data reader variable
Dim reader As OdbcDataReader = Nothing
MsgBox(reader)
Try
'open connection
Dim conn As New OdbcConnection(connString)
conn.Open()

'execute query

Dim cmd As New OdbcCommand(sql, conn)
reader = cmd.ExecuteReader


'Display output header
Console.WriteLine("Hello")
Console.WriteLine("Quering Database {0} with query {1}" & _
ControlChars.NewLine, conn.Database, cmd.CommandText)
Console.WriteLine("First Name" & ControlChars.Tab & _
"Last Name" + ControlChars.Lf)
'process the result

While reader.Read()
Console.WriteLine("{0} | {1}", _
reader("First Name").ToString().PadLeft(10), _
reader(1).ToString().PadLeft(10))

End While


Catch e As Exception
Console.WriteLine("Error: ")
' MsgBox(e)
' Finally
'close reader
reader.Close()
End Try


End Sub
 
Error in code

Not sure where you are with this, seeing this is a month old... however:

VB.NET:
[COLOR="SeaGreen"]' Declare data reader variable[/COLOR]
Dim reader As OdbcDataReader = [B]Nothing[/B]
[I][B]MsgBox(reader)[/B][/I]

Your reader is set to nothing and then you try to access it a line after.
 
Back
Top