Reputation: 489
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?
Upvotes: 1
Views: 6171
Reputation: 12047
In you're AddWithValue
you need to include the @ symbol on the front of the parameter, so:
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.
Anyway, try the above and it should update as expected.
Edit to Add
The CommandText
will always only have the @value
in there, it will not substitue the parameter values into the string.
You would need to loop through the cmd.Parameters
collection to write out the values.
Upvotes: 4