我在数据Access类中创建了一个方法,用于从带有参数的数据库中选择数据。我只想使用参数化查询。
方法是:
public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
DataTable dataTable = new DataTable();
dataTable = null;
DataSet ds = new DataSet();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myCommand.ExecuteNonQuery();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(ds);
dataTable = ds.Tables[0];
}
catch (SqlException e)
{
return null;
}
finally
{
myCommand.Connection = CloseConnection();
}
return dataTable;
}
但我无法理解如何使用此方法获取数据以及如何传递参数?
我的查询可能是"select password from tblUsers where email=@email"
如何在业务层传递@email?
如何在数据访问类中创建获取标量值的方法?
public string getpasswrd(string unm)
{
con.Open();
string cpaswrd;
cmd1 = new SqlCommand("select password from tbl_login where username='" + unm + "'", con);
cpaswrd = (String)cmd1.ExecuteScalar();
con.Close();
return cpaswrd;
}
答案 0 :(得分:3)
SqlParameter param;
cmd1 = new SqlCommand("select password from tbl_login where username=@username, con);
param = new SqlParameter("@username", SqlDbType.VarChar);
param.Direction = ParameterDirection.Input;
param.Value = unm;
cmd1.Parameters.Add(param);
cpaswrd = cmd1.ExecuteScalar().ToString();
答案 1 :(得分:1)
您只需要在sql参数中使用相同的名称:
new SqlParameter("email", "myemail@gmail.com")