sql—在vb.net中将“string”转换为“sqlcommand”

ryhaxcpt  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(338)

我是一个vb程序员新手。我相信这很简单,但我做不好。
“string”类型的值无法转换为“sqlcommand”
这就是错误。

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

如何将字符串sql转换为sqlcommand?我很感激你的帮助。

acruukt9

acruukt91#

您可以在这里看到创建命令的各种方法。https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.-ctor?view=dotnet-plat-ext-3.1
您应该使用using…end using块,这样您的连接和命令将被关闭和释放,但是您需要在使用这些对象的本地方法中使用它们。
我不得不猜测数据库中字段的类型和大小。检查数据库并相应地更正代码。

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

相关问题