如果在 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/