"Bairstow"附近的语法不正确。我在 sql 服务器中存储的播放器名称出现错误


protected void btn_Save_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox status = row.Cells[1].FindControl("cb_Cap") as CheckBox;
//int Credits = Convert.ToInt32(row.Cells[0].Text);
string Name = Convert.ToString(row.Cells[0].Text);
if (status.Checked)
{
updaterow(Name, "Captain");
}
else
{   
updaterow(Name, "None");
}
}
}
private void updaterow(string Name, string markstatus)
{
string mycon = @"Data Source=DESKTOP-7IGRD5VSQLEXPRESS; Initial Catalog =ULogin; Integrated Security = True";
string updateData = "Update teamf set role='" + markstatus + "' where Name=" + Name;
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand(updateData);
cmd.Connection = con;
cmd.ExecuteNonQuery();
lbl_Cap.Text = "Captain Added";
con.Close();
}

这比你所知道的还要糟糕。在当前代码中,如果出现异常,con.Close();行将不会运行。如果这种情况经常发生,您可以完全脱离连接运行SqlServer,并有效地将自己锁定在数据库之外。

更糟糕的是,我可以使用Name值在您的服务器上运行我想要的任何任意代码,只需以'';开头即可。想象一下,如果我决定告诉你我的名字是'';Drop Table teamf;。仔细想想会发生什么。

这应该可以解决这两个问题,并解决您的问题:

private void updaterow(string Name, string markstatus)
{
string mycon = @"Data Source=DESKTOP-7IGRD5VSQLEXPRESS; Initial Catalog =ULogin; Integrated Security = True";
string updateData = "UPDATE teamf SET role= @Role WHERE Name = @Name";
using (var conn = new SqlConnection(mycon))
using (var cmd = new SqlCommand(updateData, conn))
{ 
// Use actual column types and lengths from the database here
cmd.Parameters.Add("@Role", SqlDbType.NVarChar, 25).Value = markstatus;
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 25).Value = Name;
con.Open();
cmd.ExecuteNonQuery();
} //using block will guarantee the connection is closed, *even if an exception is thrown*
lbl_Cap.Text = "Captain Added";
}

始终始终始终使用这样的参数将数据放入查询中!任何不足之处实际上都是乞求在一年后醒来,发现你在六个月前被黑客入侵。如果应用程序中有任何或任何其他代码使用这样的字符串串联来构建SQL,那么修复它(因为它确实被破坏了(是首要任务。

问题出在您的查询上

string updateData = "Update teamf set role='" + markstatus + "' where Name=" + Name;

Name应该有引号。使用单引号更新您的查询

string updateData = $"UPDATE teamf SET role='{markstatus}' WHERE Name='{Name}'";

相关内容

最新更新