用于插入的 ExecuteNonQuery() [英] ExecuteNonQuery() for Insert

查看:32
本文介绍了用于插入的 ExecuteNonQuery()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can you please tell me what's wrong with this code?

我需要使用 DataAdapter 来插入表格吗?

Do I need to use DataAdapter to insert into a table?

我知道 connectionString 没问题,因为我在服务器资源管理器上对其进行了测试.

I know the connectionString is ok, because I tested it on the Server Explorer.

    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() 之后就失败了,不知道为什么.

The above code fails just after ExecuteNonQuery() and can´t figure why.

目标字段 (SQL Server 2008):

TARGET FIELDS (SQL Server 2008):

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

我收到的异常是:Connection property has not initialized

推荐答案

这段代码有一些问题.

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

The most significant is that you aren't setting the Command's Connection property, so the command has no way of knowing how to connect to the database.

我还强烈建议使用 使用,以及参数化您的查询:

I would also strongly recommend utilizing using, and also parameterizing your query:

最后,除非需要,否则不要在函数之外声明连接和命令.您应该只在需要时保持连接和命令.

Finally, don't declare the connection and command outside of the function unless you need to. You should only keep the connection and command around for as long as you need them.

所以你的函数最终看起来像:

So your function would end up looking like:

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 阻止

Note that currently, you will be returning 0 all the time. Rather than having to check the value returned from the function, the above example will simply throw an exception. This makes for slightly cleaner code (as the caller would have to understand that 0 is an error condition), and, if you needed to handle the exception, simply wrap the call to this function in a Try-Catch block

这篇关于用于插入的 ExecuteNonQuery()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆