Issue with connection string in web config file

拈花ヽ惹草 提交于 2020-01-01 05:38:05

问题


I am trying to set the mysql connection in web config file.

Here is the connection string code:

    <connectionStrings>
    <add name="connstring" 
         connectionString="DRIVER={MySQL ODBC= 3.51=        Driver};Database=marctest;Server=localhost;UID=root;PWD=1234;" 
         providerName="System.Data.SqlClient"/>
    </connectionStrings>

and i am accessing it in following step:

    MySqlConnection connmysql = new MySqlConnection(WebConfigurationManager.ConnectionStrings["connstring"].ConnectionString);

When I run my code it generates a null reference exception."Object reference not set to an instance of an object."

How can I resolve this issue?


回答1:


If you are using the MySql .Net Connector then your configuration setting should look similar to the following

<add name="connstring" connectionString="server=localhost;User Id=root;Persist Security Info=True;database=marctest;password=PASSWORD" providerName="MySql.Data.MySqlClient"/>

Then your code should look like.

using (MySqlConnection dbConn = new MySqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString)) 
{ 
    // Database work done here 
}



回答2:


I think you have MySql Connector/Net API. Change the ProviderName attribute and have a look at ConnectionStrings. It should be MySql.Data.MySqlClient and use System.Configuration.ConfigurationManager.ConnectionStrings collection.




回答3:


You should check the following first:

ConfigurationManager.ConnectionStrings["connstring"].ConnectionString

returns a string, you can write it to output with Response.Write or look at it using the debugger

if you have the string from the step above, check to see the class WebConfigurationManager that you are using is instantiated and is not null.

if you don't get string from the 1st step, you might have another web.config in your code folder which would be a virtual directory and could be overriding your web.config

Your connectionStrings section should be inside configuration of Web.config file and should look like following

<configuration>
  <connectionStrings>
    <add name="connstring" connectionString="..." providerName="..." />
  </connectionStrings>

  <appSettings>
  ...
  </appSettings>
</configuration>

try reading the connection string from a pure *.ASPX page and see if you can access it first.

create an ASPX file and paste following in it and call it from your browser.

<%@ Page Language="C#" %>
<% 
Response.Write(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString); 
%>

if still you cannot read the connection string, please edit your question and add full web.config and also class file that you are trying to create your connection for me to see what might go wrong



来源:https://stackoverflow.com/questions/8697251/issue-with-connection-string-in-web-config-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!