Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with connection string in web config file

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?

like image 730
NIMISH DESHPANDE Avatar asked Jan 02 '12 03:01

NIMISH DESHPANDE


People also ask

How do you define a connection string in web config file?

<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System. Data. SqlClient" />

Is it safe to store connection string in web config?

config based connectionstring as seems is unsafe, because one can read it. But think about it, if a person can read your web. config, means he can edit any file on your server anyways as he probably already hack or gain access to file.

What is SQL connection string in web config?

string strcon = ConfigurationManager. ConnectionStrings["Dbconnection"]. ConnectionString; SqlConnection DbConnection = new SqlConnection(strcon);

How do you read connection string from configuration file in code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].


2 Answers

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 
}
like image 79
Lloyd Avatar answered Sep 30 '22 20:09

Lloyd


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.

like image 39
KV Prajapati Avatar answered Sep 30 '22 19:09

KV Prajapati