I get a System.NullReferenceException when I'm using MySqlDataReader after I've inserted or updated something in the database.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
using (var conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mysqlconn"].ConnectionString))
{
conn.Open();
using (MySqlCommand comm = conn.CreateCommand())
{
comm.CommandText = "UPDATE zs_orders SET orderNo = @orderNo, firstSent = @firstSent WHERE ID = @id";
comm.Parameters.AddWithValue("orderNo", "dasda");
comm.Parameters.AddWithValue("firstSent", DateTime.Now);
comm.Parameters.AddWithValue("id", Convert.ToInt32(3));
comm.ExecuteNonQuery();
comm.Cancel();
comm.Dispose();
}
conn.Close();
}
using (var myConn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mysqlconn"].ConnectionString))
{
myConn.Open();
using (MySqlCommand cmd = new MySqlCommand("select * from zs_customers;", myConn))
{
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read()) // << Error
{
//....
}
dr.Close();
myConn.Close();
}
}
}
}
And here is the error:
System.NullReferenceException – Object reference not set to an instance of an object.
Row 45: using (MySqlDataReader dr = cmd.ExecuteReader()) Row 46: { Row 47 >>>: while (dr.Read()) Row 48: { Row 49: //....
[NullReferenceException: Object reference not set to an instance of an object.] zs_test.Page_Load(Object sender, EventArgs e) in c:\Users\JennyJ\skydrive\www\wwwroot\zs-test.aspx.cs:47
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51 System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
zs_customers
table isn't empty? Because you insertingzs_orders
tables.. And3
is anint
, there is no point to use it likeConvert.ToInt32(3)
– Soner Gönül