C#返回mysql的行数

时间:2014-03-13 01:43:21

标签: c# mysql

如果在php中我们可以做一些像$ result是一些查询的地方:

$result = mysql_query("SELECT * FROM student");
if (mysql_num_rows($results) !==0)
{
//do operation.
}  
else 
echo "no data found in databasae";  

如果我想用C#语言做这件事,那相当于什么?请告知。

5 个答案:

答案 0 :(得分:2)

我使用mysql创建了一个完整的控制台应用程序。在您的选择查询中,您正在查询整个表,这是一个坏主意。使用limit只获得一个结果 - 这应该足以确定表中是否有任何行。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql;
using MySql.Data.MySqlClient;


namespace ConsoleApplication29
{
    class Program
    {
        static void Main(string[] args)
        {
            if (AnyRows())
            {
                Console.WriteLine("There are rows in the database");
            }
            else
                Console.WriteLine("no data found in database");

            //This will pause the output so you can view the results. Otherwise you will see the dos screen open then close.
            Console.Read();
        }

        //This is the Methos to call
        public static bool AnyRows()
        {
            string connectionString = "Server=localhost;Database=test;Uid=root;Pwd=yourpassword;";

            //Wrap this is using clause so you don't have to call connection close
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                string query  = "select * from mytable limit 1";

                using (MySqlCommand command = new MySqlCommand(query, connection))
                {
                    MySqlDataReader reader = command.ExecuteReader();
                    return reader.HasRows;
                }
            }
        }
    }
}

答案 1 :(得分:1)

假设"结果"是int

类型
if(results != 0)
{
   //do operation
}
else
{
   Console.WriteLine("..."); //or output elsewhere
}

c# if else

答案 2 :(得分:1)

添加对linq的引用,它变得非常简单

var result = SomeDatabaseCall();
if (result.Any()){
    // do something
}

如果您想进一步过滤结果,可以在Any

中进行
var result = SomeDatabaseCall();
if (result.Any(r => r.ID == SomeID)){ // ID can be replaced with any properties in your return model
    // do something
}

答案 3 :(得分:0)

我得到了解决方案。它实际上非常简单。顺便说一句,谢谢那些帮助的人。这是解决方案:

class DBConnect
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    public DBConnect()
    {
        Initialize();
    }

    private void Initialize()
    {
        server = "your_server";
        database = "your_db";
        uid = "usr";
        password = "pwd";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
    }

    //open connection to database
    private bool OpenConnection()
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (MySqlException ex)
        {
            //When handling errors, you can your application's response based on the error number.
            //The two most common error numbers when connecting are as follows:
            //0: Cannot connect to server.
            //1045: Invalid user name and/or password.
            switch (ex.Number)
            {
                case 0:
                    MessageBox.Show("Cannot connect to server.  Contact administrator");
                    break;

                case 1045:
                    MessageBox.Show("Invalid username/password, please try again");
                    break;
            }
            return false;
        }
    }

    //Close connection
    private bool CloseConnection()
    {
        try
        {
            connection.Close();
            return true;
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message);
            return false;
        }
    }  


public void Select()
    {
            string query = "SELECT * FROM table";

            //Open connection
            if (this.OpenConnection() == true)
            {
                //Create Command
                MySqlCommand cmd = new MySqlCommand(query, connection);

                //Create a data reader and Execute the command
                MySqlDataReader dataReader = cmd.ExecuteReader();

                //Read the data in the database

                if (dataReader.HasRows == true)
                {
                    while (dataReader.Read())
                    {
                        //do retrieve data
                    }
                }else
                {
                    MessageBox.Show("There's no recods in the database");
                }
           }
     }
}

答案 4 :(得分:0)

最好使用SELECT 1而不是从数据库中获取不必要的数据来简单地检查是否存在行。

public static bool IsTableEmpty(string tableName)
{
    string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
    using (var conn = new MySqlConnection(cs))
    {
       conn.Open();
       string sql = string.Format("SELECT 1 FROM {0}", tableName);
       using (var cmd = new MySqlCommand(sql, conn))
       {
          using (var reader = cmd.ExecuteReader())
          {
             return !reader.HasRows;
          }
       }
    }
}

如果您想获得行数,那么您需要以下内容:

public static int GetTableRowCount(string tableName)
{
    string cs = "Server=localhost;Database=test;Uid=root;Pwd=sesame;";
    using (var conn = new MySqlConnection(cs))
    {
       conn.Open();
       string sql = string.Format("SELECT COUNT(*) FROM {0}", tableName);
       using (var cmd = new MySqlCommand(sql, conn))
       {
          return Convert.ToInt32(cmd.ExecuteScalar());
       }
    }
}