简体   繁体   English

如何使用VB.Net连接更新查询?

[英]How to Concatenate in an Update Query using VB.Net?

How do I Concatenate ProjFed (a string) with YrNbr (the value of a field in the data table) in an Update query? 如何在Update查询ProjFed (字符串)与YrNbr (数据表中字段的值)连接? With my code as shown below I get an error that says: No value given for one or more required parameters. 如下所示,通过我的代码,我得到一个错误,指出: No value given for one or more required parameters.

cmd.CommandText = "UPDATE tblProjection SET YrFed1 = ProjFed & YrNbr"
cmd.ExecuteNonQuery()

I have tried all kinds of combinations and none of the have worked. 我尝试了各种组合,但都没有奏效。 I get various error messages. 我收到各种错误消息。

I passed your variables to the procedure. 我将您的变量传递给了过程。 I assumed both are strings because you are using the ampersand to concatenate them. 我假设这两个都是字符串,因为您使用的是&符号来连接它们。 The Using blocks make sure you database objects are closed and disposed. 使用块可确保关闭并处置数据库对象。

I had to guess at what provider you are using. 我不得不猜测您正在使用什么提供程序。 It could be OleDbConnection and Command or MySql etc. 可能是OleDbConnection和Command或MySql等。

You can pass the connection string directly to the constructor of the connection and, likewise, pass the command text and the connection directly to the constructor of the command. 您可以将连接字符串直接传递给连接的构造函数,同样,可以将命令文本和连接直接传递给命令的构造函数。

Parameters help you avoid Sql Injection which can destroy your database. 参数可帮助您避免可能会破坏数据库的Sql Injection。 I also had to guess at the datatype of YrFed1. 我还不得不猜测YrFed1的数据类型。 Check your database for the actual datatype. 检查数据库中的实际数据类型。

VERY IMPORTANT! 很重要!

As @Ken White mentioned in his comment. 正如@肯·怀特(Ken White)在评论中提到的那样。 This Update statement will update every record in the table because there is no where clause. 因为没有where子句,所以此Update语句将更新表中的每个记录。

Private Sub OPCode(ProjFed As String, YrNbr As String)
    Using cn As New SqlConnection("Your connection string"),
            cmd As New SqlCommand("UPDATE tblProjection SET YrFed1 = @Yr", cn)
        cmd.Parameters.Add("@Yr", SqlDbType.VarChar).Value = ProjFed & YrNbr
        cn.Open()
        cmd.ExecuteNonQuery()
    End Using
End Sub

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

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