C#返回mysql的行数

标签 c# mysql

如果在 php 中我们可以做一些类似 where $result is some query 的事情:

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

如果我想在 C# 语言中执行此操作,这相当于什么?请指教。

最佳答案

我已经使用 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;
                }
            }
        }
    }
}

关于C#返回mysql的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22367484/

相关文章:

MySQL:将 3 个查询合并为一个

mysql - 显示每个员工的不同记录

JavaEE MySQL 连接 : No suitable driver found

Python mysql错误查询

c# - 在数组循环的末尾插入句点

c# - 具有骨骼及其矩阵的 3D 动画

c# - 通过 ASP.NET MVC 中的自定义操作过滤器重定向到自定义 View

c# - C# 中的嵌套结构是好是坏

c# - 抽象类的对象和抽象类的对象列表有什么区别?

mysql - 获取表中重复记录出现的次数