我正在尝试更新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;
}
我会尝试使[和]或(和)靠近用户名,但这仍然行不通。
答案 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.sumScore
和ClsGlobal.DoneLevels
作为参数传递,而不是浪费查询字符串。