Get the parameter prefix in ADO.NET

后端 未结 2 1682
南旧
南旧 2021-02-09 08:30

I want to generate several SQL statements based on a column list using the column names as parameters.

Edit: C#

var columns = new string         


        
相关标签:
2条回答
  • 2021-02-09 08:44

    There are 2 DbCommandBuilder methods that will help you, GetParameterName and GetParameterPlaceholder. These are protected, so you'll need a little reflection to use them.

    Check out my answer to the following question for an implementation (also included in the DbExtensions library):

    What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

    0 讨论(0)
  • 2021-02-09 08:59

    I found the answer, but I cannot reproduce how I found it:

    http://www.codewrecks.com/blog/index.php/2007/09/06/about-parametermarkerformat/

    The DbConnection can provide a schema table that also contains the correct format strings for creating command parameter names, except for SqlClient!!

    DbProviderFactory myFactory = DbProviderFactories.GetFactory(myProviderName);
    
    using (DbConnection myConnection = myFactory.CreateConnection())
    {
        myConnection.ConnectionString = mySettings.ConnectionString;
        myConnection.Open();
    
        string parameterMarker = myConnection
            .GetSchema(DbMetaDataCollectionNames.DataSourceInformation)
            .Rows[0][DbMetaDataColumnNames.ParameterMarkerFormat].ToString();
    
        myConnection.Close();
    }
    

    For SqlCclient parameterMarker is {0} but should be @{0}. I'll investigate a bit more to find out what is contained in the other schema table columns.

    0 讨论(0)
提交回复
热议问题