Claire
Claire

Reputation: 454

How do I update a row of data using c# and sql

I'm trying to update an image field where the id is equal to the row selected.

I've tried using the below code

String query = "UPDATE ArticlesTBL SET ArticleImg = VALUE (@ArticleImg) WHERE ArticleID = VALUE (@id)";              
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleImg", "UploadedUserFiles/" + FileUpdate.FileName);
myCommand.Parameters.Add(new SqlParameter("@id", ThisID));

myinfo.Text = query;

But I don't know where to place commas, brackets etc in the query string. I have a text box outputting my command and it shows that i'm using UPDATE ArticlesTBL SET ArticleImg = @ArticleImg WHERE ArticleID = @id But I'm not actually accessing the parameters. So, how do I access these parameters? Thanks

Upvotes: 0

Views: 91

Answers (1)

Steve
Steve

Reputation: 216352

The correct syntax for your update statement is

String query = @"UPDATE ArticlesTBL 
                 SET ArticleImg = @ArticleImg 
                 WHERE ArticleID = @id";

And to avoid confusion with the constructor of an SqlParameter that accepts a SqlDbType and an Object I suggest to use AddWithValue also for the ID

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@ArticleImg", "UploadedUserFiles/" + FileUpdate.FileName);
myCommand.Parameters.AddWithValue("@id", ThisID);
myCommand.ExecuteNonQuery();

Of course, the command needs to be executed after you have prepared the command text, added its parameters and associated the connection

Upvotes: 2

Related Questions