从数据库中检索记录,获取错误为“无效列名”;在SQL
本文关键字:无效 无效列名 SQL 检索 数据库 记录 取错误 获取 | 更新日期: 2023-09-27 18:17:54
我正在尝试使用下面的代码搜索我的数据库中的员工名称。但我得到了一个错误,如"无效的列名"。但我可以找到一个整数字段使用相同的编码。
源代码:
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!";
}
}
通常情况下,您可以将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));
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);
}
}