简体   繁体   中英

Error while executing query in C#, SQL Server: trying to update if value already present else insert

I am trying to execute a query with a condition like if username already present then update the row, else insert username and password.

This is my code below:

using (SqlCommand cmd = new SqlCommand("INSERT INTO Users(Username,Password) VALUES(@User,@password) ON DUPLICATE KEY UPDATE Username=VALUES(Username), Password=VALUES(Password)"))
{
    cmd.Connection = con;
    cmd.Parameters.AddWithValue("@User", TextBox3.Text);
    cmd.Parameters.AddWithValue("@password", Pwd);

    con.Open();
    cmd.ExecuteNonQuery();
}

I got the following error:

Incorrect syntax near the keyword 'ON'.

I am not able to figure out what is wrong in this. Can anyone please help me out?

In SQL Server you need to use a query something like this:

-- check if exists (by username) - if found, update password
IF EXISTS (SELECT * FROM dbo.Users WHERE Username = @User)
   UPDATE dbo.Users
   SET Password = @password
   WHERE Username = @User
ELSE
   INSERT INTO dbo.Users(Username, Password) 
   VALUES(@User, @password) 

And as mentioned in my comments - do not use the .AddWithValue function (see linked blog post for details) but use this instead:

cmd.Parameters.Add("@User", SqlDbType.VarChar, 100).Value = TextBox3.Text;

And also, please do not store your passwords in clear text in the database!

It looks like you're using MySQL syntax. I don't think SQL Server has ON DUPLICATE KEY. You'd probably want a MERGE statement .

@marc_s

 String query = @"IF EXISTS (SELECT * FROM Users WHERE     Username = @ User)
       UPDATE Users
       SET Password = @password
       WHERE Username = @ User
    ELSE
       INSERT INTO Users(Username, Password) 
       VALUES(@ User, @password)";
                    using (SqlCommand cmd = new SqlCommand(query)) 

I used the code you gave and used to debug points to check if the code is executing ,and it was, still it is not updating or Inserting the values .I cant run the query in SQL server cause each time i open the query window VSudio restarts,i am using trial version of Visual Studio

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