【问题标题】:Microsoft Access Parameter Query Fails OccasionallyMicrosoft Access 参数查询偶尔失败
【发布时间】:2009-08-26 13:56:34
【问题描述】:

我有一个查询,基本上是这样说的:

SELECT DISTINCT [DB_ID]
FROM [TableX]
WHERE ([ForeignKey]=@ForeignKey);

一旦我有了这个,我会返回第一个 DB_ID(应该只有一个)。

我为调用它而编写的例程是用 C# 编写的,因此无论 DB_ID 的名称是什么,我都可以获取任何表名的数据库 ID。

大部分 ForeignKey 参数是整数,但有些是字符串值。然后,要添加参数值,我使用

Parameter.AddWithValue(ForeignKeyName, objValue);

这个例程对现有的数据库 ID 非常有效;但是,当找不到 ForeignKey 时,它会返回 3 而不是 null。

我意识到我可以使用蛮力技术并简单地编写两种样式的 SQL 语句(一种接受整数,另一种接受字符串)并完全避免参数,但我想知道并理解为什么这个参数化例行程序不起作用。

有人可以向我解释为什么这不起作用吗?

/// <summary>
/// Locates the Primary Key Value for a Table using the Table's Foreign Key
/// </summary>
/// <param name="tableName">Name of the Table to Delete from</param>
/// <param name="primaryKey">Name of the Primary Key in the Table</param>
/// <param name="foreignKey">Name of the Foreign Key in the Table</param>
/// <param name="id">Foreign Key Value to Search for in the Table</param>
/// <returns>Primary Key Database ID for this Table Record</returns>
List<int> tableSelectId(string tableName, string primaryKey, string foreignKey, object id) {
  string sqlText = string.Format("SELECT DISTINCT [{0}] " +
    "FROM [{1}] WHERE ([{2}]=@id);", primaryKey, tableName, foreignKey);
  DataTable table = new DataTable("IDs");
  OleDbDataAdapter da = new OleDbDataAdapter(sqlText, AccessConnection);
  da.SelectCommand.Parameters.AddWithValue("@id", id);
  try {
    da.Fill(table);
  } catch (OleDbException err) {
    clsLogger.LogException((Exception)err);
  }
  List<int> vals = new List<int>(table.Rows.Count);
  foreach (DataRow row in table.Rows) {
    vals.Add((int)row[0]);
  }
  return vals;
}

eof

【问题讨论】:

    标签: parameters sqlparameter


    【解决方案1】:

    重温一下:原来另一位开发人员正在从事同一个项目,他复制了一个不同的数据库来工作,该数据库有一个空表。

    该表前一小时有记录,下一小时没有!

    简而言之,上面的代码 sn-p 就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多