vb.net 使用VB在ASP.net中对Sql服务器的参数化更新查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13452998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parameterized Update Query for Sql server in ASP.net with VB
提问by saurabhsood91
I am trying to write a paramaterized update query to insert values into an Sql Server Express Database. The query I have written is:
我正在尝试编写一个参数化更新查询以将值插入到 Sql Server Express 数据库中。我写的查询是:
Dim cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandText = "update tblposts set title=@ptitle, pdate=@pd,
content=@pcontent where pid=@p"
cmd.Parameters.AddWithValue("ptitle", txtTitle.Text)
cmd.Parameters.AddWithValue("pcontent", txtcontent.InnerText)
cmd.Parameters.AddWithValue("pd", DateTime.Now.ToString)
cmd.Parameters.AddWithValue("p", postid)
On running cmd.ExecuteNonQuery, I get number of rows affected as 1, but the change is not reflected in the database.
在运行时cmd.ExecuteNonQuery,受影响的行数为 1,但更改未反映在数据库中。
On printing the query using Debug.Write, I get the query not with the parameter values, but the names of the parameters itself (ie. @pcontent, @title etc)
在使用 打印查询时Debug.Write,我得到的查询不是参数值,而是参数本身的名称(即@pcontent、@title 等)
What can be the mistake here?
这里有什么错误?
回答by RemarkLima
In you're AddWithValueyou need to include the @symbol on the front of the parameter, so:
在你AddWithValue需要在参数的前面包含@符号,所以:
cmd.Parameters.AddWithValue("@ptitle", txtTitle.Text)
cmd.Parameters.AddWithValue("@pcontent", txtcontent.InnerText)
cmd.Parameters.AddWithValue("@pd", DateTime.Now.ToString)
cmd.Parameters.AddWithValue("@p", postid)
I'm guessing that it's executing correctly but there where clause is blank, so perhaps updating a blank row.
我猜它正在正确执行,但是 where 子句是空白的,所以也许更新了一个空白行。
Anyway, try the above and it should update as expected.
无论如何,请尝试上述操作,它应该会按预期更新。
Edit to Add
编辑添加
The CommandTextwill always only have the @valuein there, it will not substitue the parameter values into the string.
该CommandText会永远只能有@value在那里,它不会substitue参数值到字符串。
You would need to loop through the cmd.Parameterscollection to write out the values.
您需要遍历cmd.Parameters集合以写出值。

