From time to time I have to do some "real" programming (well, more real than IEC 61131 anyway). It's not really my forté.
All I want to do in the example below is connect to an MS Embedded SQL database file, select everything from it (about 12 rows) and display the number of rows in a message box. It halts with a null reference error at line 23.
I'm using
this msdn site as a reference. I've cut it down for now just to demonstrate it has a connection - the db has a few dummy rows of data just to prove a point. I can't see what I've got wrong, which no doubt means it's blindingly obvious.
I have previously managed to use just a CreateCommand() and an ExecuteNonQuery() to insert the data into the db file, so I know that my connection string works, the file's OK and the path is valid; however the sqlcedataadapter looks like the right way to do what I need to do.
Help?
Code:
Public Class Form1
' the filespec, connection and so forth will be used by multiple forms.
Public FileSpec As String
Public dbConnString As String
Public dbConn As New SqlServerCe.SqlCeConnection("data source = Databases\testdb.sdf")
Public Sub main()
Dim dbSqlQuery1 As String
Dim dbRecords As SqlServerCe.SqlCeDataAdapter = Nothing
Try
dbConn.Open()
' Select Statement
Dim dbCommand1 As New SqlServerCe.SqlCeCommand
dbSqlQuery1 = "select * from accomponent"
dbCommand1 = dbConn.CreateCommand()
dbCommand1.CommandText = dbSqlQuery1 ' fails at this point with a null reference error
dbRecords.SelectCommand = dbCommand1 ' and suggests I define dbCommand1 as "new", which I have
' Populate a dataset
Dim dbDataSet As New DataSet()
dbRecords.Fill(dbDataSet)
' Prove that data exist in the table (should show 12 rows)
MessageBox.Show("Number of Rows: " & dbDataSet.Tables(0).Rows.Count)
Finally
dbConn.Close()
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Otherwise not much happens...
main()
End Sub
End Class