C# MySQL参数化查询问题

标签 c# mysql

我有以下用于从数据库填充 DAO 的方法。它执行 3 次读取 - 一次读取主要对象,2 次读取一些翻译。

public bool read(string id, MySqlConnection c)
{
    MySqlCommand m = new MySqlCommand(readCommand);
    m.Parameters.Add(new MySqlParameter("@param1", id));
    m.Connection = c;
    MySqlDataReader r = m.ExecuteReader();
    r.Read();
    accountID = Convert.ToInt32(r.GetValue(0).ToString());
    ...
    comment = r.GetValue(8).ToString();
    r.Close();
    m = new MySqlCommand(getAccountName);
    m.Parameters.Add(new MySqlParameter("@param1", accountID));
    m.Connection = c;
    r = m.ExecuteReader();
    r.Read();
    account1Name = r.GetValue(0).ToString();
    r.Close();
    m = new MySqlCommand(getAccountName);
    m.Parameters.Add(new MySqlParameter("@param1", secondAccountID));
    m.Connection = c;
    r = m.ExecuteReader();
    r.Read();
    account2Name = r.GetValue(0).ToString();
    r.Close();
    return true;
}

account2Name = r.GetValue(0).ToString(); 行上,我收到以下错误:

Invalid attempt to access a field before calling Read()

我不明白问题出在哪里 - 上一行调用了 read!

最佳答案

这似乎在您的代码中更早地起作用了。您确定那里有要读取的值(即您的查询是否返回 0 行或 null 或其他无法转换为字符串的内容?)

关于C# MySQL参数化查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/832916/

相关文章:

c# - 为什么我的 ASP.NET Core 2 方法不能返回 TwiML?

MYSQL:加载数据文件但如果找到相同的键则更新?

mysql - 更新 MySQL 中的大量数据

C# 指针 : error CS0254: The right hand side of a fixed statement assignment may not be a cast expression

c# - 为什么 DllImport for C bool as UnmanagedType.I1 throws but as byte it works

c# - 错误 : 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T'

c# - HashSet<T> 和 Linq 查询的性能

php - 需要帮助检查用户是否在线

mysql - oracle "initialization parameters"和 "session parameters"之间有什么区别?

php - 多个唯一值 MYSQL