0

I am a novice vb programmer. I am sure it's simple but I can't get it right.

Value of type 'String' cannot be converted to 'SQLCommand'

It is the error.

Public Sub InsertPackageDetails(ByVal PackageName As String, ByVal PackageDescription As String, ByVal DateOfInstallation As DateTime, ByVal ImportPackageStatus As String)
    Dim SQL As String = "Insert into PackageInstallation(PackageName,PackageDescription,DateOfInstallation,ImportPackageStatus) values('" + PackageName + "','" + PackageDescription + "','" + DateOfInstallation + "'," + ImportPackageStatus + ") "
    DBHelper2.ExecuteNonQuery(SQL)
End Sub

How can I convert SQL which is the string to SQLCommand? I appreciate the help.

2
  • 5
    SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection - check out Little Bobby Tables Commented May 31, 2020 at 6:03
  • There's no implicit conversion between a string and SqlCommand. You need to create a new instance of the SqlCommand class and pass the query text to it. Commented Jun 1, 2020 at 10:55

1 Answer 1

2

You can see the various ways to create a command here. https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.-ctor?view=dotnet-plat-ext-3.1

You should use Using...End Using blocks so that your connection and command will be closed and disposed but you will need to have these objects in the local method where they are used.

I had to guess at the type and size of your fields in the database. Check in the database and correct the code accordingly.

Public Sub InsertPackageDetails(ByVal PackageName As String, ByVal PackageDescription As String, ByVal DateOfInstallation As DateTime, ByVal ImportPackageStatus As String)
    Dim SQL As String = "Insert into PackageInstallation(PackageName,PackageDescription,DateOfInstallation,ImportPackageStatus) 
                          Values(@PackageName, @PackageDescription, @DateOfInstallation, @ImportPackageStatus;"
    Using cn As New SqlConnection("Your connection string"),
            cmd As New SqlCommand(SQL, cn)
        With cmd.Parameters
            .Add("@PackageName", SqlDbType.VarChar, 100).Value = PackageName
            .Add("@PackageDescription", SqlDbType.VarChar, 100).Value = PackageDescription
            .Add("@DateOfInstallation", SqlDbType.DateTime).Value = DateOfInstallation
            .Add("@ImportPackageStatus", SqlDbType.VarChar, 100).Value = ImportPackageStatus
        End With
        cn.Open()
        cmd.ExecuteNonQuery()
    End Using
End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.