如何从数据表中获取单列值

本文关键字:获取 单列值 数据表 | 更新日期: 2023-09-27 18:20:57

我有一个表

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

其中conntype具有pop3或imap等值。考虑一个用户是loggedin。我想获取登录用户的connType值,以进行类似的操作

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

我该怎么做

如何从数据表中获取单列值

正如上面评论中提到的,有很多文档涵盖了这一点。有许多方法可以连接到数据库并检索信息,如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。注意,如果您期望返回多行(我假设ID是这里的主键),则需要将SqlDataReader与cmd一起使用。ExecuteReader函数。

请注意,我正在使用字符串。Equals()而不是connType=="Imap",这是为了允许我指定不区分大小写。

希望这能帮助