2016-04-25 6 views
1

私は、データアクセスクラスで1つのメソッドを作成して、パラメータを使用してデータベースからデータを選択しました。私はパラメータ化されたクエリを使いたいだけです。パラメータ付きクエリのデータアクセスクラスでメソッドを作成するにはどうすればよいですか?

方法は以下のとおりである。

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 protected]"かもしれません。どのように@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; 

    } 

答えて

1

あなたは、SQLのパラメータに同じ名前を使用する必要があります。 new SqlParameter("email", "[email protected]")

3
SqlParameter param; 

    cmd1 = new SqlCommand("select password from tbl_login where [email protected], con); 

    param = new SqlParameter("@username", SqlDbType.VarChar); 
    param.Direction = ParameterDirection.Input; 
    param.Value = unm; 
    cmd1.Parameters.Add(param); 

    cpaswrd = cmd1.ExecuteScalar().ToString(); 
関連する問題