Apostrophe (single quote) in connection string

后端 未结 2 908
别那么骄傲
别那么骄傲 2021-01-13 04:20

I\'m having a trouble with the \' character in a connection string. Entity Framework throws an exception saying:

Format of the initializ

相关标签:
2条回答
  • 2021-01-13 05:04

    I have finally stumbled upon a correct answer. It appears, you have to surround the value with single quotes and additionally duplicate the inner apostrophe in order to escape it, like this:

    Password='test''password'

    This is such a dumb problem to waste this much time on. I hope it saves somebody time in the future.

    Thanks to everyone for participating.

    0 讨论(0)
  • 2021-01-13 05:20

    Assuming it is the password which contains a single quote, you should try enclosing the password in xml encoded double-quotes, something like this :

    <connectionStrings>
      <add name="MyConnectionString" connectionString="Data Source=.;
        Initial Catalog=MYDB; User ID=MyUser;Password=&quot;my'password&quot;;
        providerName="System.Data.SqlClient";/>
    </connectionStrings>
    

    Assuming you are not in Xml context (as mentionned by @PanagiotisKanavos ) the ConnectionString initialization would look like :

    var conn = new SqlConnection("Data Source=.;
        Initial Catalog=MYDB; User ID=MyUser;Password=\"my'password\";
        providerName="System.Data.SqlClient")
    
    0 讨论(0)
提交回复
热议问题