I am trying to write a paramaterized update query to insert values into an Sql Server Express Database. The query I have written is:
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.
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)
What can be the mistake here?
In you’re
AddWithValueyou need to include the @ symbol on the front of the parameter, so:I’m guessing that it’s executing correctly but there where clause is blank, so perhaps updating a blank row.
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.You would need to loop through the
cmd.Parameterscollection to write out the values.