简体   繁体   English

ADO.NET中参数化SQL命令的最终形式

[英]Final form of parametric SQL commands in ADO.NET

I am getting a syntax error when I send a parameterized query to Access from my C# program via ADO.NET. 当我通过ADO.NET从C#程序向Access发送参数化查询时,出现语法错误。

I, of course, know what SQL string I have included in my code, with the parameter names embedded inside. 我当然知道我的代码中包含了什么SQL字符串,并且参数名称嵌入其中。

Does anyone know how I can look at the SQL string that is finally sent to the DBMS during after I call cmd.ExecuteNonQuery ? 有谁知道在调用cmd.ExecuteNonQuery之后如何查看最终发送到DBMS的SQL字符串?

Thanks. 谢谢。

EDIT: 编辑:

There is no way to see that string in the interactive debugger or in an Access log or something? 没有办法在交互式调试器或访问日志中看到该字符串? In order for anyone to reproduce my precise problem, they would have to have my database, which isn't going to happen. 为了让任何人重现我的确切问题,他们都必须拥有我的数据库,而这不会发生。 However, since interest has been expressed in the details of what I'm trying to do I'm publishing the following code fragment: 但是,由于已经对我要执行的操作的细节表达了兴趣,因此我将发布以下代码片段:

  OdbcCommand cmd = new OdbcCommand();
  cmd.CommandText = 
     @"insert into Posts (Page, Line, TimeStamp, Status) values
           (@pagename, @lineno, @now, 'SAVED')";
  cmd.Connection = _cn;
  cmd.Transaction = transaction;
  cmd.Parameters.Add(new OdbcParameter("@pagename",OdbcType.VarChar));
  cmd.Parameters.Add(new OdbcParameter("@lineno",OdbcType.VarChar));
  cmd.Parameters.Add(new OdbcParameter("@now",OdbcType.DateTime));
  cmd.Parameters["@pagename"].Value = pageId;
  cmd.Parameters["@lineno"].Value = lineId;
  cmd.Parameters["@now"].Value = now;
  cmd.ExecuteNonQuery();

I hope it helps. 希望对您有所帮助。

Thanks again. 再次感谢。

EDIT: 编辑:

It occurs to me that "TimeStamp" may be a reserved word in AccessSQL and this is likely the cause of the syntax error. 在我看来,“ TimeStamp”可能是AccessSQL中的保留字,这很可能是语法错误的原因。 However, even assuming this is the cause, the general question of how to see the SQL query in its final form remains open. 但是,即使假设这是原因,如何查看最终形式的SQL查询的一般问题仍然存在。

Access only uses positional parameters. 访问仅使用位置参数。

All you need to do is change your SQL to this: 您需要做的就是将您的SQL更改为此:

insert into Posts (Page, Line, [TimeStamp], Status) values (?, ?, ?, 'SAVED')

making sure to put any additional parameters into the Parameters collection in the proper order. 确保以适当的顺序将任何其他参数放入“ Parameters集合。

Edit: Updated to solve the reserved-word issue. 编辑:更新以解决保留字的问题。

Edit: It is not possible to trace the SQL that gets run on an OLE DB connection, at least not currently. 编辑:不可能跟踪在OLE DB连接上运行的SQL,至少当前不会。 See this Microsoft KB article . 请参阅此Microsoft KB文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM