C#MySQL选择表

时间:2015-10-27 18:19:13

标签: c# mysql

我的代码只选择第一个条目,但我需要选择表格中的所有条目。有什么办法吗?谢谢!

 public string getSiteForRotator()
    {
        string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
        string Connect = "connection_string";
        MySqlConnection myConnection = new MySqlConnection(Connect);
        MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
        myConnection.Open();
        MySqlDataReader MyDataReader;
        MyDataReader = myCommand.ExecuteReader();

        while (MyDataReader.Read())
        {
            string url = MyDataReader.GetString(0);
            string desc = MyDataReader.GetString(1);
            int timer = MyDataReader.GetInt32(2);
            return url+"," + desc+"," + timer.ToString();
        }
        MyDataReader.Close();
        myConnection.Close();
        return "ERROR";
    }

2 个答案:

答案 0 :(得分:0)

 public string getSiteForRotator()
    {
        string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
        string Connect = "connection_string";
        MySqlConnection myConnection = new MySqlConnection(Connect);
        MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
        myConnection.Open();
        MySqlDataReader MyDataReader;
        MyDataReader = myCommand.ExecuteReader();

        string url = "";
         while (MyDataReader.Read())
        {
            url = MyDataReader.GetString(0);
            string desc = MyDataReader.GetString(1);
            int timer = MyDataReader.GetInt32(2);
            url+"," + desc+"," + timer.ToString();
        }
        MyDataReader.Close();
        myConnection.Close();
        return url;
    }

这有用吗?你在while循环中使用return语句,也就是说它只显示单个记录。

答案 1 :(得分:0)

因为现在你的代码只返回第一条记录,因为在while循环中,你在第一个循环中退出方法,返回将第一条记录中的数据连接在一起。如果你想要返回所有记录 最简单的方法是使用DataTable

public DataTable getSiteForRotator()
{
    DataTable result = new DataTable();
    string CommandText = "SELECT `url`, `desc`, `timer` FROM sites";
    string Connect = "connection_string";
    using(MySqlConnection myConnection = new MySqlConnection(Connect))
    using(MySqlDataAdapter da = new MySqlDataAdapter(CommandText))
        da.Fill(dt);
    return dt;
}

在您的调用代码中,您可以检查表中是否有行,如果有任何行,则使用该行

DataTable result = getSiteForRotator();
if(result.Rows.Count == 0)
    Console.WriteLine("No rows found");

else
    ... use the rows of the datatable ....