0

我正在尝试使用以下代码在我的数据库中搜索员工姓名。但是我得到了一个错误,比如"Invalid column Name"。但我可以使用相同的编码找到一个整数字段。

源代码:

protected void btnSearch_Click(object sender, EventArgs e)
{
    cnn.ConnectionString = "Data Source=.;Initial Catalog=Students;Integrated Security=True";
    cnn.Open();

    string sqlStr = "select * from emp where Name="+txtName.Text+"";
    SqlDataAdapter da = new SqlDataAdapter(sqlStr,cnn);
    DataSet ds = new DataSet();
    da.Fill(ds);

    if (ds.Tables[0].Rows.Count != 0)
    {
        msgLbl.Text = "Record found!";
    }
    else
    {
        msgLbl.Text = "Record not found!";
    }
}
4

2 回答 2

4

通常您会将 sqlStr 组装为:

string sqlStr = "select * from emp where Name='"+txtName.Text+"'";

注意搜索词周围的单引号。

但是,SQL 注入注释暗示您的表达式应该是:

string sqlStr = "select * from emp where Name=@StudentName";

后跟:

da.Parameters.add(new SQLParameter("@StudentName", (object)txtName.text));

于 2013-06-12T04:52:18.720 回答
0
private void btnsearch_Click(object sender, EventArgs e)
    {
        try
        {
            Dbconnection db = new Dbconnection();

            DataTable dt = db.getTable("Select * from view_Cust where CustomerNo=" + txtCustomerNo.Text + "");

            if (dt.Rows.Count > 0)
            {
                Cust_Id = (int)dt.Rows[0]["Cust_ID"];
                txtCustomerName.Text = dt.Rows[0]["Name"].ToString();

                DataTable dt1 = db.getTable("Select * from view_CustomerBalance where CustomerNo=" + txtCustomerNo.Text + "");

                if (dt1.Rows.Count > 0)
                {

                    txtCustomerBalance.Text = dt1.Rows[0][2].ToString();
                    btnsave.Text = "Update";

                }
            }
            else
            {
                MessageBox.Show("Record Not Found...");

            }
        }
        catch (Exception e1)
        {
            MessageBox.Show(e1.Message);

        }


    }
于 2016-09-28T06:20:03.030 回答