I’m developing a class to manage the operations on a Mysql database.
I have the following code:
using System;
using MySql.Data.MySqlClient;
public class MysqlAccess
{
private MySqlConnection pCnn;
public enum OperationType {Select = 1,Insert = 2,Update = 3,Delete = 4};
public MysqlAccess()
{
MySqlConnection Connection=new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LocalMySqlServer"].ConnectionString);
}
public MySqlConnection Connection { get {return pCnn;} set {pCnn=value;} }
public int Connect()
{
try
{
Connection.Open();
if (Connection.State == System.Data.ConnectionState.Open)
{
return 1;
}
else
{
return 0;
}
}
catch (Exception e)
{
return -1;
}
}
}
}
Page Load Code
protected void Page_Load(object sender, EventArgs e)
{
MysqlAccess DBManager = new MysqlAccess();
DBManager.Connect();
Response.Write("Connection State:" + DBManager.Connection.State.ToString());
}
When i do the response.write the connection is null, why?
Thanks in advance!
Well, it is null because you never really initialize the
Connectionproperty and it will be null until you initialize it. So instead of:initialize the property:
While this might fix the NullReferenceException you are getting you should be aware that
MySqlConnectionimplements IDisposable meaning that you should make sure to call the Dispose method to avoid leaking connections or creating new connections on each request which could be particularly catastrophic in a web application.