从SQL中检索记录获取错误为“无效列名称”?

时间:2013-06-12 04:24:12

标签: c# asp.net

我正在尝试使用以下代码在我的数据库中搜索员工姓名。但是我收到了像“无效的列名称”这样的错误。但我可以使用相同的编码找到一个整数字段。

源代码:

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!";
    }
}

2 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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);

        }


    }