0

所以本质上,我有两个文本字段,一个是学生的名字,一个是学生的姓氏。我希望程序做的是:

使用TextBox上面的名字和姓氏返回学生的电话号码和评论。这是我到目前为止所拥有的:

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();
}

我不知道从这里去哪里。在代码中我放置了两个注释语句,所以我在我的作业的两个不同部分使用了上面的语句,但是当我把它们放在一起时,它就不起作用了。

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

4

2 回答 2

1

我假设你得到一个错误,是吗?您正在尝试对同一个命令对象执行两个操作,而我模糊的回忆说那是行不通的。尝试删除此行。

        cmd.ExecuteNonQuery();

如果您研究过 using 语句,那通常是处理连接和阅读器等资源的更好解决方案。

于 2012-10-27T18:32:26.437 回答
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();
}
于 2012-10-27T21:30:24.110 回答