简体   繁体   English

sql update命令的vb.net问题

[英]vb.net problem with sql update command

I'm looking for some help trying to figure out why I'm seeing a SQL error on an update command within vb.net, noting that my SQL experience is very limited. 我正在寻找一些帮助,以弄清为什么我在vb.net中的更新命令上看到SQL错误,并指出我的SQL经验非常有限。

I'm in the midst of building a profile system that will be used in several other tools within our company, as part of the profile system, the user's information is queried against our LDAP directory upon page load and the data stored in variables displayed in labels on the page. 我正在构建一个配置文件系统,该配置文件系统将在我们公司的其他多个工具中使用,作为配置文件系统的一部分,页面加载时将根据我们的LDAP目录查询用户信息,并且将数据存储在页面上的标签。

The user then has the option to create a new profile if one does not exist, or update an existing if there is already one in place. 然后,用户可以选择创建一个新的配置文件(如果不存在)或更新现有的配置文件(如果已经存在)。 The code determines the proper action based on a query to the table using the users employee id. 该代码基于使用用户员工ID对表的查询来确定适当的操作。

My insert command works ok but the update does not, below is my current code and the error. 我的插入命令可以正常运行,但更新不起作用,以下是我当前的代码和错误。

This is the insert statement to create a new entry, this works properly. 这是用于创建新条目的插入语句,可以正常工作。

    Protected Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
    Try
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand

        con.ConnectionString = "Data Source="server" Catalog=usertable;Integrated Security=True"

        con.Open()
        cmd.Connection = con

        cmd.CommandText = "INSERT INTO Profile (FirstName, LastName, Email, Telephone, EmployeeID, NTLogin) VALUES ('" & lblFirstName.Text & "','" & lblLastName.Text & "','" & lblEmail.Text & "','" & lblPhone.Text & "','" & lblEID.Text & "','" & lblNT.Text & "')"

        cmd.ExecuteNonQuery()
        btnInsert.Enabled = False
        lblValid.Text = "Record Inserted Successfully"
        con.Close()
    Catch ex As System.Exception
        lblValid.Text = (ex.Message)

    End Try

The following is the update code that gives an error: 以下是给出错误的更新代码:

Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
    Try
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand

        con.ConnectionString = "server;Initial Catalog=usertable;Integrated Security=True"
        con.Open()
        cmd.Connection = con

        cmd.CommandText = "UPDATE Profile (FirstName, LastName, Email, Telephone, EmployeeID, NTLogin) VALUES ('" & lblFirstName.Text & "','" & lblLastName.Text & "','" & lblEmail.Text & "','" & lblPhone.Text & "','" & lblEID.Text & "','" & lblNT.Text & "') Where [EmployeeID] = '" & lblEID.text & "'"

        cmd.ExecuteNonQuery()
        btnUpdate.Enabled = False
        lblValid.Text = "Record Updated Successfully"
        con.Close()
    Catch ex As System.Exception
        lblValid.Text = (ex.Message)
    End Try
End Sub

The exception error returned is 返回的异常错误是

    [SqlException (0x80131904): Incorrect syntax near '('.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +392
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4515
   System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +1390
   System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +538
   System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +290
   newprofile.btnUpdate_Click(Object sender, EventArgs e) +759
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +155
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804

I'm at a loss and appreciate any help that can be given. 我很茫然,感谢能提供的任何帮助。

Update syntax is completely invalid as stated by @JBKing. 如@JBKing所述,更新语法完全无效。

Update statements are of form: 更新语句的形式为:

UPDATE myTableName SET field=new_value WHERE condition=some_value

Also, to avoid possible injections, do not pass field values directly into SQL command. 另外,为避免可能的注入,请勿将字段值直接传递到SQL命令中。 Use parameters How to use parameters "@" in an SQL command in VB 使用参数如何在VB中的SQL命令中使用参数“ @”

cmd.CommandText = "UPDATE Profile (FirstName, LastName, Email, Telephone, EmployeeID, NTLogin) VALUES ('" & lblFirstName.Text & "','" & lblLastName.Text & "','" & lblEmail.Text & "','" & lblPhone.Text & "','" & lblEID.Text & "','" & lblNT.Text & "') Where [EmployeeID] = '" & lblEID.text & "'"

Should be like this: 应该是这样的:

cmd.CommandText = "UPDATE Profile SET FirstName='"&lblFirstName.Text&"', LastName='"&lblLastName.Text&"', Email='"&lblEmail.Text&"', Telephone='"&lblPhone.Text&"', EmployeeID='"&lblEID.Text&"', NTLogin='"&lblNT.Text&"' Where [EmployeeID] = '" & lblEID.text & "'"

I would be careful about last names like "O'Connor" that may break with your SQL as there are reasons stored procedures or parameters are preferred in most cases to prevent SQL injection attacks. 对于可能会破坏您的SQL的诸如“ O'Connor”之类的姓氏,我会非常小心,因为在大多数情况下,最好使用存储过程或参数来防止SQL注入攻击。

Thanks to everyone who provided some assistance. 感谢所有提供帮助的人。 Between the examples and links shared, I was able to rebuild my command so that it update properly and is now setup using parametrized queries rather than a direct insert statement, or at least what appears correct to me, and is working. 在示例和共享的链接之间,我能够重建命令以使其正确更新,并且现在可以使用参数化查询而不是直接插入语句(或者至少对我而言正确的语句)进行设置,并且可以正常工作。

Below is my final code. 下面是我的最终代码。

Try
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand

        con.ConnectionString = "Data Source=server;Initial Catalog=database;Integrated Security=True"
        con.Open()
        cmd.Connection = con
        cmd.CommandText = ("UPDATE Profile SET FirstName = @FirstName, LastName = @LastName, Email = @Email, Telephone = @Telephone, EmployeeID = @EmployeeID, NTLogin = @NTLogin, Organization = @Organization, Permission = @Permission Where [EmployeeID] = '" & eID & "'")
        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = lblFirstName.Text
        cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = lblLastName.Text
        cmd.Parameters.Add("@Email", SqlDbType.VarChar).Value = lblEmail.Text
        cmd.Parameters.Add("@Telephone", SqlDbType.VarChar).Value = lblPhone.Text
        cmd.Parameters.Add("@EmployeeID", SqlDbType.VarChar).Value = lblEID.Text
        cmd.Parameters.Add("@NTLogin", SqlDbType.VarChar).Value = lblNT.Text
        cmd.Parameters.Add("@Organization", SqlDbType.VarChar).Value = lblOrg.Text
        cmd.Parameters.Add("@Permission", SqlDbType.VarChar).Value = "requestor"

        cmd.ExecuteNonQuery()
        con.close
        lblValid.Text = "Record Updated Successfully"
    Catch ex As System.Exception
        lblValid.Text = (ex.Message)
    End Try

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM