什么是PHP的mysql_fetch_array函数的C#等价物?

我正在学习C#/ ASP.NET,我想知道以下PHP代码的C#等价物是什么?
我知道userid,我想从这个表中获取变量“row”的数组,所以我可以将它用作“row [‘name’]”和“row [’email’].

$result = mysql_query("SELECT email, name FROM mytable WHERE id=7");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    printf("Email: %s  Name: %s", $row["email"], $row["name"]);
}

谢谢.

最佳答案
我不确定这是否与mysql_fetch_array相同,但我认为.
您可以使用IDBCommmand.ExecuteReader创建IDataReader并使用它来填充包含该行的所有字段的Object [].

例如(使用SQL-Server):

// use using statements to ensure that connections are disposed/closed (all implementing IDisposable)
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
using (var cmd = new SqlCommand("SELECT email, name FROM mytable WHERE id=@id", con))
{
    cmd.Parameters.AddWithValue("@id", ID);  // use parameters to avoid sql-injection
    con.Open();
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        { 
            var fields = new object[reader.FieldCount];
            // following fills an object[] with all fields of the current line, 
            // is this similar to mysql_fetch_array?
            int count  = reader.GetValues(fields);
        }
    }
}

编辑:

I don’t mean to make it as similar as possible, but how would I go about getting the same end result (a variable with the results) in C#

这是一个品味问题.您可以使用某种ORM,如Enity-Framework,NHibernate,LINQ-To-SQL或Stackoverflow的Micro-ORM Dapper.NET(我当前正在使用的)或普通的ADO.NET(如上所示).

您可以使用手动填充的自定义类与DataReader或DataTable自动加载架构.

例如(这里使用MySQL):

DataTable tblEmail = new DataTable();
using (var con = new MySqlConnection(Properties.Settings.Default.MySQL))
using (var da = new MySqlDataAdapter("SELECT Email, Name FROM Email WHERE id=@id", con))
{
    da.SelectCommand.Parameters.AddWithValue("@id", ID);
    da.Fill(tblEmail);
}

if (tblEmail.Rows.Count == 1)
{
    DataRow row  = tblEmail.Rows[0];
    String email = row.Field<String>("Email");
    String name  = row.Field<String>("Name");
}

如您所见,.NET中有很多种方法.我用ADO.NET只显示了两个.

转载注明原文:什么是PHP的mysql_fetch_array函数的C#等价物? - 代码日志