在我的应用程序中,我允许用户在单击删除按钮时从网格视图中删除整行。但我在删除查询中收到错误。错误是“无效的列名称” 我的代码如下:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Username" AutoGenerateColumns="false" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
<asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="true" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="true" />
<asp:BoundField DataField="Password" HeaderText="Password" ReadOnly="true" />
<asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="true" />
<asp:CommandField ShowDeleteButton="true" />
</Columns>
</asp:GridView>
C#代码是:
SqlConnection conn = new SqlConnection(@"Data Source=CHINNU-PC\SQLEXPRESS; Initial Catalog= CarDetails; Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvbind();
}
}
protected void gvbind()
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From [User]", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
public void Delete(string UserName)
{
string sql = "Delete From [User] Where UserName=" + UserName;
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Delete(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
gvbind();
}
答案 0 :(得分:4)
你会得到很多关于SQL注入等的评论......
但是,为了回答 - 您需要在SQL语句中将UserName
包装在单引号中。
所以这个 -
string sql = "Delete From [User] Where UserName=" + UserName;
应该是这样的:
string sql = "Delete From [User] Where UserName='" + UserName + "'";
答案 1 :(得分:0)
此代码对SQL Injection攻击非常开放,只需输入'OR 1 = 1;-作为用户名或密码即可显示所有用户名和密码。 创建SQL语句的方法使您的应用程序容易受到SQL注入的攻击,这是某人入侵站点的最常见方法之一。与其这样做,不如使用参数化查询。