gpt4 book ai didi

c# - 更新后 MySqlDataReader NullReferenceException

转载 作者:行者123 更新时间:2023-11-30 01:16:51 33 4
gpt4 key购买 nike

在数据库中插入或更新某些内容后使用 MySqlDataReader 时,我收到 System.NullReferenceException。

这是我的代码:

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();
}
}
}
}

这是错误:

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

最佳答案

在从 SqlDataReader 读取数据之前使用 if(dr.HasRows) 以避免 System.NullReferenceException – 未将对象引用设置为对象的实例。

关于c# - 更新后 MySqlDataReader NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18975083/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com