tags:

views:

24

answers:

1

Hey everyone. I'm fairly new to VB.NET and I'm looking to create a module that will contain all general SQL functionality like connect, disconnect and execute a sql query etc.

I think I'm almost there but the code keeps bombing in one place.

Can anyone see what is wrong with the following code?

It bombs here, setting the command object to a connection object. The opening and closing of the connection works fine.

cmdSystem.Connection = cnSystem

Or maybe I'm just thinking old VB and am going about this all wrong.

Public Module modGeneral

Private cnSystem As New SqlClient.SqlConnection
Private cmdSystem As SqlClient.SqlCommand

Public Sub ConnectToSQL()

    Dim sConnectionString As String = "Data Source=SQL;Initial Catalog=XXXX;User ID=XXXX;Password=XXXX"

    Try
        cnSystem.ConnectionString = sConnectionString
        cnSystem.Open()
    Catch ex As Exception

    End Try

End Sub
Public Sub DisconnectFromSQL()

    Try
        cnSystem.Close()
        cnSystem.Dispose()
    Catch ex As Exception

    End Try

End Sub
Public Function lExecuteSQL(ByVal sSQL As String) As Long

    Dim lRecordsAffected As Long = 0

    Try
        cmdSystem.Connection = cnSystem
        cmdSystem.CommandText = sSQL
        lRecordsAffected = cmdSystem.ExecuteNonQuery()
        cmdSystem.Dispose()
    Catch ex As Exception

    End Try

    Return lRecordsAffected

End Function

End Module

Thanks in advance.

+1  A: 

at some point, you need to instantiate your command object like you did the connection.

have you considered having these functions in a class instead of a module?

Beth
I created a class module but ran into the same problem so I figured it must be some .NET thing I was not getting so I just moved it into a module. When you say instantiate the command I thought that's already being done as when I type in cmdSystem in the code window it comes up with the objects properties and I can select the Connection property but it doesn't accept the connection object for it. Could you explain further what you mean by instansiating the object? Thanks =)
Tom
you need to create a new instance of the object, either when you declare it, like you did with the connection, or before you use it.
Beth
Nevermind, I just had to add New to the command object declaration. Seems to be working now and I can continue. Thanks. Edit: =)
Tom