Insert的ExecuteNonQuery()

时间:2013-07-18 16:34:20

标签: vb.net visual-studio sql-server-2008 insert executenonquery

你能告诉我这段代码有什么问题吗?

我是否需要使用DataAdapter插入表格?

我知道connectionString没问题,因为我在服务器浏览器上测试了它。

    Dim mydao As New Connection
    Dim connectionString As String = mydao.GetConnectionString()
    Dim connection As New SqlConnection(connectionString)
    Dim cmd As New SqlCommand

Public Function add(ByVal area As String, ByVal user As String) As Integer

        cmd.CommandText = "INSERT into Area (Area, user) VALUES ('" + area + "','" + user + "')"
        Try
            connection.Open()
            Dim cant As Integer = cmd.ExecuteNonQuery()'it throws exception here
            connection.Close()
            Return cant
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return 0
        End Try

    End Function

上面的代码在ExecuteNonQuery()之后失败,无法解释原因。

TARGET FIELDS(SQL Server 2008):

AREA        varchar(100)  NOT NULL ,
USER        varchar(100)  NOT NULL 

我收到的例外是:Connection property has not initialized

1 个答案:

答案 0 :(得分:9)

此代码存在一些问题。

最重要的是您没有设置Command的Connection属性,因此该命令无法知道如何连接到数据库。

我还强烈建议您使用using,以及parameterizing您的查询:

最后,除非您需要,否则不要在函数外部声明连接和命令。只要你需要它们,你就应该保持连接和命令。

所以你的功能最终会像:

Public Function add(ByVal area As String, ByVal user As String) As Integer

    Dim mydao As New Connection

    Using connection As New SqlConnection(mydao.ConnectionString())

        Using command As New SqlCommand()
            ' Set the connection
            command.Connection = connection 

            ' Not necessary, but good practice
            command.CommandType = CommandType.Text 

            ' Example query using parameters
            command.CommandText = "INSERT into Area (Area, user) VALUES (@area, @user)" 

            ' Adding the parameters to the command
            command.Parameters.AddWithValue("@area", area)
            command.Parameters.AddWithValue("@user", user)

            connection.Open()

            Return command.ExecuteNonQuery()

        End Using ' Dispose Command

    End Using ' Dispose (and hence Close) Connection

End Function

请注意,目前,您将一直返回0。上面的例子只是抛出一个异常,而不是必须检查函数返回的值。这使得代码稍微更清晰(因为调用者必须理解0是错误条件),并且,如果您需要处理异常,只需将调用包装在Try-Catch块中