c#返回mysql的行数

本文关键字:mysql 返回 | 更新日期: 2023-09-27 17:50:00

如果在php中我们可以这样做,其中$result是一些查询:

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

如果我想在c#语言中这样做,那么这个等价于什么?请建议。

c#返回mysql的行数

我已经使用mysql创建了一个完整的控制台应用程序。在select查询中,您查询整个表,这是一个坏主意。使用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;
                }
            }
        }
    }
}

假设"results"为int类型

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

c# if else

为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
}

我找到解决办法了。其实很简单。顺便说一句,谢谢那些帮助我的人。解决方案如下:

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

最好使用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());
       }
    }
}