开发者

C# - SQL Server - ? parameters and Oledb

开发者 https://www.devze.com 2022-12-12 20:09 出处:网络
I am writing a small framework in C# for importing data to SQL Server. I have noticed that if you try to use the ? placeholder for parameters, they do not work if you use the System.Data.SqlClient na

I am writing a small framework in C# for importing data to SQL Server.

I have noticed that if you try to use the ? placeholder for parameters, they do not work if you use the System.Data.SqlClient namespace开发者_运维知识库.

However, if you use the System.Data.OleDb namespace for working with the database, they work just fine. (you just have to add Provider=SQLOLEDB in your connect string)

So I have a few questions, because the ? syntax is required by my solution:

  1. Is there an alternative to using named parameters with System.Data.SqlClient? I want to use ordered parameters.
  2. Is there any performance impact to using one namespace (ado provider) over the other?
  3. Is there any other reason I should prefer one namespace over the other?

To elaborate on what I'm trying to do, my framework is going to take a class decorated with some custom attributes and generate SQL like so:

INSERT INTO myTable (col1, col2, ...) VALUES (?, ?, ...)

This string will be created with one IDbCommand and several IDataParameters and for each ExecuteNonQuery it will merely set the values on the IDataParameters.

Any thoughts?

Edit: I tried using named parameters as p0, p1, etc. as an answerer mentioned and it is working pretty well on SqlClient. However if I use Oledb, it errors saying:

"Must declare the scalar variable @p0."

My parameter is created like so:

new OleDbParameter("p" + index, GetType(attribute)); 
//GetType does work to get the correct SqlDbType

What is wrong? I also tried adding and removing the @ symbol in the parameter name to no avail.

FINAL EDIT: I just made Oledb use ? and SqlClient use named parameters. I can change back and forth for new providers.


Thats the behaviour of those classes. OleDb uses ?, SqlClient named parameter.

Perfomance: I have no benchmarks, but I think the SqlClient should perform better with an Sql Server than OleDB. SqlClient is explicit for Sql Server, OleDB for any kind of Datasource (even Excel). But pls. try it out.

With SqlClient you can also have "ordered parameter". Just call you parameter @Param1, @Param2, @Param3....


You can use this as a ref for the params

SqlCommand.Parameters Property

0

精彩评论

暂无评论...
验证码 换一张
取 消