2012-01-22 4 views
0

から単一の列の値を取得するためにどのようにCONNTYPEがPOP3またはIMAPのような値を持つテーブルデータテーブル

Login(id(int),EmailId(varchar(35),connType(varchar)) 

を有しています。ユーザーがログインしていると考えてください。私はこの

if(conntypeValue == imap) 
{ 
//code for imap connection 
}else 
{ 
//code for pop3 connection 
} 

これをカバーするドキュメントがたくさんある上記のコメントで述べたように、私はそれを

答えて

0

をどのように行うことができますように行うにはログインしているユーザーのCONNTYPE値を取得したいです。データベースに接続し、Linq2SqlやNHibernateなどの情報を取得する方法はたくさんあります。私は基本的なSqlConnectionクラスを使ってこれを行いました。個人的には、最初にこれらの概念を理解することが重要であると感じています。

public SqlConnectionExample() 
    { 
     // the connection string to the database - this should ALWAYS be configurable 
     string connectionString = "server=localhost;initial catalog=mydatabase; user=mysqluser;pass=mysqlpassword"; 
     int userID = 1; // the ID of the logged in user 

     // create a connection to the database 
     using (SqlConnection conn = new SqlConnection(connectionString)) 
     { 
      conn.Open(); 
      // create a command to pass over the connection 
      using (SqlCommand cmd = new SqlCommand("select connType from login where ID = @id", conn)) 
      { 
       // create a SQL parameter to add them to the command - this will limit the results to the single user 
       SqlParameter p = new SqlParameter("id", System.Data.SqlDbType.Int); 
       p.Value = userID; 

       cmd.Parameters.Add(p); 

       // as we are only selecting one column and one row we can use ExecuteScalar 
       string connType = cmd.ExecuteScalar().ToString(); 

       if (connType.Equals("imap", StringComparison.CurrentCultureIgnoreCase)) 
       { 
        // imap 
       } 
       else 
       { 
        // pop3 
       } 
      } 
     } 
    } 

正しいConnectionString(www.connectionstrings.comを試してみてください)とUserIDを自分で決定する必要があります。注:IDNが主キーであると仮定していますが、複数の行が返されることが予想される場合は、cmd.ExecuteReader関数でSqlDataReaderを使用する必要があります。

注意connType == "Imap"ではなくstring.Equals()を使用しています。これは大文字と小文字の区別を指定できます。

希望すると便利です。