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?
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System. Data. SqlClient" />
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.
string strcon = ConfigurationManager. ConnectionStrings["Dbconnection"]. ConnectionString; SqlConnection DbConnection = new SqlConnection(strcon);
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With