且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在OleDB中将表名作为参数传递?

更新时间:2023-10-06 11:32:34

您不是将表名作为参数传递,而是将您的 @Name 值作为参数传递.如果需要,您不能将表名作为参数传递甚至.参数仅用于值,而不是表或列名称.您只是在格式化基于查询的表名.据我所知,您使用命名参数的问题.OleDb 提供程序不支持命名参数.

You are not passing table name as a parameter, you are passing your @Name value as a parameter. You can't pass a table name as a parameter even if you want. Parameters only for values, not table or column names. You are just formatting your query based table name. As far as I see, your problem using named parameters. OleDb provider does not support named parameters.

来自 OleDbCommand.Parameters

OLE DB .NET Provider 不支持命名参数传递SQL 语句或调用的存储过程的参数当 CommandType 设置为 Text 时,OleDbCommand.在这种情况下,必须使用问号 (?) 占位符.例如:

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:

SELECT * FROM Customers WHERE CustomerID = ?

SELECT * FROM Customers WHERE CustomerID = ?

因此,OleDbParameter 对象添加到OleDbParameterCollection 必须直接对应的位置命令文本中参数的问号占位符.

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

试试看;

string query = String.Format("INSERT INTO {0} (Name) VALUES (?)", tablename);
...
cmd.Parameters.AddWithValue("@name", name);

还使用 using 语句处理您的 OleDbConnectionOleDbCommand.

Also use using statement to dispose your OleDbConnection and OleDbCommand.

using(OleDbConnection connection = new GetConnection())
using(OleDbCommand cmd = con.CreateCommand())
{

}

并考虑使用 .Add 方法 代替 .AddWithValue.它可能会导致一些问题.阅读 我们可以停止使用 AddWithValue() 已经?

And consider to use .Add method instead .AddWithValue. It may cause some problems. Read Can we stop using AddWithValue() already?