返回学生信息 - SQL / C#赋值

时间:2012-10-27 18:26:12

标签: c# sql visual-studio-2012

基本上,我有两个文本字段,一个是firstName,另一个是student的lastName。我希望程序做的是:

使用上面TextBox中的firstName和lastName返回学生的电话号码和评论。这就是我到目前为止所做的:

if (actionButton.Text == "Update")
{
    SqlConnection cn;
    cn = new SqlConnection();
    cn.ConnectionString = "Data source=(local); Initial Catalog=INT422Assignment1; Integrated Security=SSPI;";
    cn.Open();
    SqlCommand cmd;
    cmd = new SqlCommand();
    cmd.Connection = cn;
    cmd.CommandText = "SELECT firstName, lastName, phoneNumber, Comments FROM myTable WHERE firstName LIKE @firstName AND lastName LIKE @lastName"; //AND lastName LIKE @lastName"
    //used this part to delete records

    SqlParameter param = new SqlParameter();
    param.ParameterName = "@firstName";
    param.Direction = ParameterDirection.Input;
    param.SqlDbType = SqlDbType.VarChar;
    param.Value = firstNameTB.Text;
    cmd.Parameters.Add(param);

    param.ParameterName = "@lastName";
    param.Direction = ParameterDirection.Input;
    param.SqlDbType = SqlDbType.VarChar;
    param.Value = lastNameTB.Text;
    cmd.Parameters.Add(param);

    //display data in a listbox
    SqlDataReader reader;
    reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        string s;
        s = reader["firstName"].ToString() + "-" + reader["lastName"].ToString() + reader["phoneNumber"].ToString() + reader["Comments"].ToString();
        MessageBox.Show(s);
    }

    cmd.ExecuteNonQuery();

    cn.Close();
}

我不知道从哪里开始。在代码中我放置了两个注释语句,所以我在我的任务的两个不同部分使用了上述内容,但是当我将它们组合在一起时,它不起作用。

发生的事情是我没有得到任何结果。基本上我需要它给我两个文本框中指示的学生的电话号码和评论

2 个答案:

答案 0 :(得分:1)

我认为你得到了一个错误,是吗?你试图在同一个命令对象上做两个操作,而我的朦胧回忆说这不会起作用。尝试删除此行。

        cmd.ExecuteNonQuery();

如果您已经研究过使用声明,那么这通常是处理连接和读者等资源的更好解决方案。

答案 1 :(得分:0)

if (actionButton.Text == "Update")
{
    SqlConnection cn = new SqlConnection();
    cn.ConnectionString = "Data source=(local); Initial Catalog=INT422Assignment1; Integrated Security=SSPI;";
    cn.Open();

    MessageBox.Show(cn.ConnectionState.ToString());
// If you are shown "Open" by above messagebox and you are using correct table and column names then you will get accurate results by following code

    SqlCommand cmd = cn.CreateCommand();
    cmd.CommandText = "SELECT firstName, lastName, phoneNumber, Comments FROM myTable WHERE firstName LIKE '" + firstNameTB.Text + "' AND lastName LIKE  '" + lastNameTB.Text + "' "; 
    SqlDataReader reader = cmd.ExecuteReader();
    string s = "";
    while (reader.Read())
    {
        s = reader["firstName"].ToString() + "-" + reader["lastName"].ToString() + reader["phoneNumber"].ToString() + reader["Comments"].ToString();
        MessageBox.Show(s);
    }    
    cn.Close();
}