我收到一个错误“关键字'where'附近的语法不正确”

时间:2019-04-14 01:50:50

标签: sql-server wpf syntax-error

我正在尝试更新SQL Server表(连接到WPF项目),并且收到消息

  

关键字WHERE附近的语法不正确

我的代码有什么问题?

private void Save_button_Click(object sender, RoutedEventArgs e)
{
    try
    {
        Select("INSERT INTO [dbo].[Users](sumScore, doneLevels) VALUES ('" + ClsGlobal.sumScore + "','" + ClsGlobal.DoneLevels + "') WHERE [userName]= '" + ClsGlobal.userName + "'");
    }
    catch (Exception ex)
    { 
        MessageBox.Show(ex.Message); 
    }
}

public DataTable Select(string selectSQL) 
{
    DataTable dataTable = new DataTable("dataBase");                                                                                         

    SqlConnection sqlConnection = new SqlConnection(@"Data Source =(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\Avraham\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB\New Database.mdf ");

    sqlConnection.Open();                                           

    SqlCommand sqlCommand = sqlConnection.CreateCommand();          
    sqlCommand.CommandText = selectSQL;                            

    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); 
    sqlDataAdapter.Fill(dataTable);                                 

    return dataTable;
}

我会尝试使[和]或(和)靠近用户名,但这仍然行不通。

1 个答案:

答案 0 :(得分:2)

此查询:

INSERT INTO [dbo].Users
    VALUES ('" + ClsGlobal.sumScore + "','" + ClsGlobal.DoneLevels + "')
   WHERE [userName]= '" + ClsGlobal.userName;

没有道理。 INSERT插入新行,因此WHERE不适合。

也许您想要UPDATE

UPDATE dbo.Users
    SET sumScore = ?,
        DoneLevels = ?
    WHERE userName = ?;

您应该以{{1​​}},ClsGlobal.sumScoreClsGlobal.DoneLevels作为参数传递,而不是浪费查询字符串。