gpt4 book ai didi

C#返回mysql的行数

转载 作者:太空宇宙 更新时间:2023-11-03 10:53:47 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com