ExecuteReader CommandText property has not been properly initialized

ECATech picture ECATech · Sep 7, 2012 · Viewed 17.8k times · Source

First of all sorry if some of the code isn't right. I'm still new to using sql on vb.net

I have the following code:

Imports MySql.Data.MySqlClient
Imports System.Data.SqlClient

Public Class Form1

    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        Dim objConn As MySqlConnection
        Dim objDataset As New DataSet
        Dim objDataAdapter As MySqlDataAdapter
        Dim myCommand As MySqlCommand

        Dim sqlConn As String

        objConn = New MySqlConnection("server=localhost;userid=root;database=attendance_system")
        myCommand = objConn.CreateCommand

        objConn.Open()
        Dim objReader As MySqlDataReader = myCommand.ExecuteReader

        sqlConn = "SELECT student_name FROM profile"
        objDataAdapter = New MySqlDataAdapter(sqlConn, objConn)
        objDataAdapter.Fill(objDataset, "profile")

        MsgBox("The Connection is Now 'OPEN'")

        objReader.Read()

        TextBox1.Text = objReader("student_name")

        objReader.Close()
        objConn.Close()
    End Sub
End Class

I am using MySQL connector via vb.net in phpmyadmin and have set a database with records. The connection string is working, but my problem is when I try to click the button to load the data in the textbox, I keep getting:

The CommandText property has not been properly initialized."

The error is on this line:

"Dim objReader As MySqlDataReader = myCommand.ExecuteReader"

I've tried a lot of fixes that I've found on this site and the others as well.

Answer

Jon Skeet picture Jon Skeet · Sep 7, 2012

This is the problem:

Dim objReader As MySqlDataReader = myCommand.ExecuteReader

sqlConn = "SELECT student_name FROM profile"

You're declared the SQL after you've tried executing the query (and even then you don't set it as the SQL for the command). How would you expect that to work? Additionally, sqlConn is a very strange name for a variable declaring the SQL - I'd expect it to be a connection.

It looks like you're trying to mix too very different ways of fetching data:

  • Reading directly from the reader
  • Filling a DataSet with a data adapter

You shouldn't be mixing them like that. Work out which you actually want to do, take out all the code related to the other style, and then make sure you're doing everything in a sensible order.