两个如何从2个不同的表中获取数据c#

时间:2016-05-14 21:26:28

标签: c# mysql mysqldatareader

我有两张桌子。我需要从食物表中获取calorificValue,并从calorie_tracker表中获取daily_gained然后进行一些计算。我写了这段代码,我知道它并不高效。它检索daily_gained但未能获得calorificValue。

MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=@name", cnn);
MySqlCommand cmd2 = new MySqlCommand("SELECT sportsman_id,daily_gained FROM myfitsecret.calorie_tracker where sportsman_id=@sportsman_id", cnn);
cmd2.Parameters.AddWithValue("@sportsman_id", Login.userID);

string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("@name",s);
cmd2.Connection.Open();
MySqlDataReader rd = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
int burned = 0;
if (rd.HasRows) // if entered username and password have the data
{
    while (rd.Read()) // while the reader can read 
    {
        if (rd["sportsman_id"].ToString() == Login.userID) // True for admin
        {
            burned += int.Parse(rd["daily_gained"].ToString());
        }
    }
}
cmd2.Connection.Close();
cmd.Connection.Open();

MySqlDataReader rd2 = cmd.ExecuteReader(CommandBehavior.CloseConnection);

if (rd2.HasRows) // if entered username and password have data
{
    while (rd2.Read()) // while the reader can read 
    {
        if (rd2["name"].ToString() == s)
        {
            burned += int.Parse(rd2["calorificValue"].ToString());
        }
    }
}
MessageBox.Show(burned+"");
DataTable tablo = new DataTable();
string showTable = "SELECT * from myfitsecret.calorie_tracker where sportsman_id=@sportsman_id";
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand showCommand = new MySqlCommand();
showCommand.Connection = cnn;
showCommand.CommandText = showTable;
showCommand.CommandType = CommandType.Text;
showCommand.Parameters.AddWithValue("@sportsman_id", Login.userID);
adapter.SelectCommand = showCommand;
adapter.Fill(tablo);

dataGridView1.DataSource = tablo;
cnn.Close();

2 个答案:

答案 0 :(得分:2)

为什么不直接使用标量函数SUM并让数据库完成其工作而不是编写大量代码?

int burned = 0;
string s = comboBox1.SelectedItem.ToString();
cnn.Open();
string cmdText = @"SELECT SUM(calorificValue) 
                   FROM myfitsecret.food 
                   WHERE name=@name";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
    cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = s;
    object result = cmd.ExecuteScalar();
    burned += (result != null ? Convert.ToInt32(result) : 0);
}
cmdText = @"SELECT SUM(daily_gained) 
            FROM myfitsecret.calorie_tracker 
            WHERE sportsman_id=@sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
    cmd.Parameters.Add("@sportsman_id", MySqlDbType.Int32).Value = Login.userID;
    object result = cmd.ExecuteScalar();
    burned += (result != null ? Convert.ToInt32(result) : 0);
}

从您的代码中看不到,但是也应该在using语句中创建连接(对于同时打开连接非常严格的MySql非常重要)

我们也可以使用不同的方法将两个命令放在一起并用分号分隔它们。这称为批处理命令,它们都只需要一次数据库就可以执行。当然我们需要使用MySqlDataReader回退,使用NextResult()方法(see here MSDN for Sql Server)将两个结果从第一个结果传递到第二个结果({{3}})

string cmdText = @"SELECT SUM(calorificValue) 
                   FROM myfitsecret.food 
                   WHERE name=@name;
                   SELECT SUM(daily_gained) 
                   FROM myfitsecret.calorie_tracker 
                   WHERE sportsman_id=@sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
    // Add both parameters to the same command
    cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = s;
    cmd.Parameters.Add("@sportsman_id", MySqlDbType.Int32).Value = Login.userID;
    cnn.Open();
    using(MySqlDataReader reader = cmd.ExecuteReader())
    {
        // get sum from the first result
        if(reader.Read()) burned += Convert.ToInt32(reader[0]);

        // if there is a second resultset, go there
        if(reader.NextResult())
           if(reader.Read())
              burned += Convert.ToInt32(reader[0]);
    }
}

答案 1 :(得分:0)

您的问题可能是关闭连接然后再次尝试打开它。无论哪种方式,关闭和打开连接都是相当低效的。

MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=@name", cnn);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("@name",s);


MySqlCommand cmd2 = new MySqlCommand("SELECT SUM(daily_gained) FROM myfitsecret.calorie_tracker where sportsman_id=@sportsman_id", cnn);
cmd2.Parameters.AddWithValue("@sportsman_id", Login.userID);
cnn.Open();

MySqlDataReader rd = cmd.ExecuteReader();

if (rd.HasRows) // if entered username and password have data
{
    while (rd.Read()) // while the reader can read 
    {
        burned += int.Parse(rd["calorificValue"].ToString());
    }
}

burned = cmd2.ExecuteScalar();
MessageBox.Show(burned+"");
cnn.Close();