简体   繁体   English

在C#,SQL Server中执行查询时出错:尝试更新已存在的值,否则插入

[英]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'. 关键字“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: 在SQL Server中,您需要使用如下所示的查询:

-- 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: 而在我的评论中提到- 使用.AddWithValue功能(见链接的博客帖子详细信息),但是用这个来代替:

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. 看起来你正在使用MySQL语法。 I don't think SQL Server has ON DUPLICATE KEY. 我认为SQL Server没有ON DUPLICATE KEY。 You'd probably want a MERGE statement . 你可能想要一个MERGE语句

@marc_s @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 我使用你提供的代码并用于调试点以检查代码是否正在执行,它仍然没有更新或插入值。我不能在SQL服务器中运行查询因为每次我打开查询窗口VSudio重启,我正在使用Visual Studio的试用版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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