OracleCommand SQL参数无法正常工作

时间:2018-06-13 07:04:11

标签: c# oracle

我的代码看起来像这样:

String Tablei= "PHGR_PHYS_GRAPH";
OracleCommand cmd_row = new OracleCommand();
OracleDataReader dr1;
cmd_row.CommandText = "SELECT PHGR_ID FROM " +":tableconf";
cmd_row.Connection = conn;
cmd_row.Parameters.Add(new OracleParameter("tableconf", Tablei));
dr1 = cmd_row.ExecuteReader();

我收到错误ORA-00903表名无效。

但是当我像这样更改查询时(没有参数):

cmd_row.CommandText = "SELECT PHGR_ID FROM PHGR_PHYS_GRAPH";

的工作原理。 谁能指出我的错误是什么?

1 个答案:

答案 0 :(得分:2)

您无法将OracleParameter用于此目的。您只能将其用于参数值。例如:

OracleCommand cmd_row = new OracleCommand();
cmd_row.CommandText = "SELECT PHGR_ID FROM PHGR_PHYS_GRAPH WHERE phgr_id=:phgr_id";
cmd_row.Connection = conn;
cmd_row.Parameters.Add(new OracleParameter("phgr_id", "some_value"));

如果您想拥有变量表名,则应使用String.Format()或更简洁的$

String Tablei= "PHGR_PHYS_GRAPH";
OracleCommand cmd_row = new OracleCommand();
cmd_row.CommandText = $"SELECT PHGR_ID FROM {Tablei} WHERE phgr_id=:phgr_id";
cmd_row.Connection = conn;
cmd_row.Parameters.Add(new OracleParameter("phgr_id", "some_value"));

BTW:我强烈建议您使用块

包装代码