简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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