0

所以在这里,我的目标是从我的数据库 STUD_DB 中选择 3 列,studentlastname、studentfirstname 和 studentmiddleinitial,所以这里是代码:

    public string selectname(string email)
{
    string name;
    SqlConnection con = new SqlConnection(constr);
    string select = "SELECT studentlastname,studentfirstname,studentmiddleinitial FROM STUD_DB WHERE emailaddress = @mail";
    SqlCommand sel = new SqlCommand(select, con);

    sel.Parameters.Add("@mail", email);

    //this is where idk what to do. 
}

我担心的是,在我选择了 3 列之后,我想将它们放在单独的变量中,然后将它们连接到一个字符串中,从而得到学生的全名,但是,我不知道如何对这部分进行编码。:) 将等待答复,谢谢。:)

4

3 回答 3

1

您的代码正确加载了数据库中的数据(始终使用参数化查询,从不使用字符串连接)。您只需要读取SqlDataReader检索到的数据。

public string selectname(string email) 
{ 
    string name; 
    using(SqlConnection con = new SqlConnection(constr))
    {
        string select = "SELECT studentlastname,studentfirstname,studentmiddleinitial " + 
                        "FROM STUD_DB WHERE emailaddress = @mail"; 
        SqlCommand sel = new SqlCommand(select, con); 
        sel.Parameters.Add("@mail", email);
        SqlDataReader dr = sel.ExecuteReader();
        while(dr.Read())
            name = string.Join(" ", dr.GetString(0), dr.GetString(1), dr.GetString(2));
    }
    return name;
}

此外,使用语句是真正的救星,这将避免忘记关闭/处理连接

于 2012-08-12T10:23:31.790 回答
1

您可以在查询中组合全名:

const string @select = "SELECT studentlastname + ' ' " +
                               "+ studentfirstname + ' ' " +
                               "+ studentmiddleinitial as FullName " +
                               "FROM STUD_DB WHERE emailaddress = @mail";


using (var connection = new SqlConnection(constr))
{
    using (var command = new SqlCommand(select, connection))
    {
        connection.Open();
        command.Parameters.Add("mail", email);
        return command.ExecuteScalar() as string;
    }
}
于 2012-08-12T10:37:22.800 回答
-1

如果您不想使用参数,您可以简单地添加字符串。不是最值得夸耀的解决方案,但会奏效。

private void GetData(String email)
{
  String sqlStatement = "select * from Programs where Something = " + email;
  try
  {
    using (SqlDataAdapter adapter = new SqlDataAdapter(sqlStatement, _CONNECTION_STRING))
    {
      DataSet dataSet = new DataSet("Items");
      adapter.Fill(dataSet, "Items");
    }
    }
  catch (Exception) { }
  // Here you just type "dataSet." and the intellisense will 
  // present you with options to access the tables, rows etc.
}
于 2012-08-12T10:07:19.730 回答