如何在一个代码中从两个不同的表中进行选择?

时间:2016-08-13 12:38:39

标签: c#

我正在使用两次sqlreader因为我必须从两个不同的表中选择如何使用一个代码执行此操作?这是我的代码:

第一个Sqlreader:

 SqlCommand sqlCmd = new SqlCommand("SELECT Name from Customers where name = '"+textview2.Text+"'", con);
        SqlDataReader sqlReader = sqlCmd.ExecuteReader();

        while (sqlReader.Read())
        {
            textview1.Text = (sqlReader["Name"].ToString());


        }
        sqlReader.Close();

第二次阅读:

SqlCommand cmd = new SqlCommand("Select Mobile from Informations where Mobile = '"+textview3.Text+"'", con);
        SqlDataReader sqlReader2 = cmd.ExecuteReader();
        while (sqlReader2.Read())
        {
            textview4.Text = (sqlReader2["Mobile"].ToString());
        }

        sqlReader2.Close();

我想创建一个代码而不是两个代码。

1 个答案:

答案 0 :(得分:2)

首先,您需要使用参数化查询。我邀请您搜索为什么这是构建SQL查询的强制方法,并尽快删除字符串连接的使用。之后,您可以将两个命令连接在一起,并使用SqlDataReader的NextResult方法来获取第二个数据

// Both commands text are passed to the same SqlCommand
string cmdText = @"SELECT Name from Customers where name = @name;
                   SELECT Mobile from Informations where Mobile = @mobile";
SqlCommand sqlCmd = new SqlCommand(cmdText, con);

// Set the parameters values....
sqlCmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = textview2.Text
sqlCmd.Parameters.Add("@mobile", SqlDbType.NVarChar).Value = textview3.Text
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.HasRows)
{
     // Should be only one record, but to be safe, we need to consume
     // whatever there is in the first result
     while(sqlReader.Read())
         textview1.Text = (sqlReader["Name"].ToString());

     // Move to the second result (if any)
     if(sqlReader.NextResult())
     {
          // Again, we expect only one record with the mobile searched 
          // but we need to consume all the possible data 
         while(sqlReader.Read())
            textview4.Text = (sqlReader["Mobile"].ToString());
     }
}
sqlReader.Close();

顺便说一下,你已经知道名字和手机了,为什么要执行这段代码?