Ksingh
Ksingh

Reputation: 3

Error: Fill: SelectCommand.Connection property has not been initialized

I'm having some trouble with this code here. I'm using it to upload information from a pre-populated listview to an SQL table on a remote server. It seems that the error:

Fill: SelectCommand.connection property has not been initialized

comes up every time I attempt to debug. This is also happening with any previous programs that I have used with the same method to upload information (they were working fine at that time)

I'm using vb 2012 + win7/win8

  Sub legitsql()
        For i As Integer = 0 To UploadMasterStudentFile.numlines - 1
            ds = New DataSet
            da = New MySqlDataAdapter("insert into SK_StudentList (studentnumber,firstname,lastname,birthdate,year) values('" & Student_Record.StudentNumber(i) & "','" & Student_Record.FirstName(i) & "','" & Student_Record.FirstName(i) & "','" & Student_Record.Birthdate(i) & "','" & Student_Record.Year(i) & "')", sqlcon)
            da.Fill(ds, "SK_StudentList")
        Next
        MessageBox.Show("Student List Updated")


    End Sub

Upvotes: 0

Views: 2832

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460208

This might be related to your problem, but however, you should dispose your connections when you're done with them. You should use the Using-statement:

Using sqlcon = New MySqlConnection(connectionString)
    Const sql = "insert into SK_StudentList (studentnumber,firstname,lastname,birthdate,year) values(?studentnumber,?firstname,?lastname,?birthdate,?year);"
    sqlcon.Open();
    For i As Integer = 0 To UploadMasterStudentFile.Count - 1
        Using cmd = New MySqlCommand(sql, sqlcon)
            cmd.Parameters.AddWithValue("?studentnumber", Student_Record.StudentNumber(i))
            cmd.Parameters.AddWithValue("?firstname", Student_Record.FirstName(i))
            cmd.Parameters.AddWithValue("?lastname", Student_Record.LastName(i))
            cmd.Parameters.AddWithValue("?birthdate", Student_Record.Birthdate(i))
            cmd.Parameters.AddWithValue("?year", Student_Record.Year(i))
            cmd.ExecuteNonQuery()
        End Using
    Next
End Using

You should also use sql-parameters to avoid sql-injection, to prevent careless mistakes and to make the code more readable in general.

Note that i've already corrected a bug in your sql-command(you've used the firstname even for the lastname). I have no idea why you are using a DataAdapter to fill DataSets on every iteration while you are inserting these records. I have omitted that part since it is pointless.

Upvotes: 1

Related Questions