简体   繁体   English

objDataReader 是 Null - ASP.NET C#

[英]objDataReader is Null - ASP.NET C#

I am quite new to ASP.NET and C#, so I still do not have much of an idea as to how things work.我对 ASP.NET 和 C# 还是很陌生,所以我对事情的运作方式仍然不太了解。 I basically get an error when I run my program and create a maintenance task.当我运行我的程序并创建维护任务时,我基本上会遇到错误。 My code is shown right below:我的代码如下所示:

private DataTable getMaintenance()
        {
            DataTable maintenance_dt = new DataTable();
            maintenance_dt.Columns.Add("maintenance_ID");
            maintenance_dt.Columns.Add("DAILY_MAINTENANCE");
            maintenance_dt.Columns.Add("ADMIN_COMMENT");
            string SQLstr = "SELECT MAINTENANCE_ID,DAILY_MAINTENANCE,ADMIN_COMMENT FROM " + maintenance_table + " where " + key + " like " + value + " order by MAINTENANCE_ID ";
            using (DataTableReader objDataReader = OS.OSFunctions.executeSQLQuery(SQLstr))
            {
                while (objDataReader.Read())
                {
                    DataRow mItem = maintenance_dt.NewRow();
                    mItem[0] = objDataReader["MAINTENANCE_ID"].ToString();
                    mItem[1] = objDataReader["DAILY_MAINTENANCE"].ToString();
                    if (objDataReader["ADMIN_COMMENT"] != DBNull.Value)
                    {
                        mItem[2] = objDataReader["ADMIN_COMMENT"].ToString();
                    }
                    else
                    {
                        mItem[2] = "";
                    }
                    maintenance_dt.Rows.Add(mItem);
                }
            }
            return maintenance_dt;
        }

The error I get from running this states我从运行这个状态得到的错误

Object reference not set to an instance of an object. Object 引用未设置为 object 的实例。 objDataReader was null objDataReader 是 null

This occurs when I attempt to create a maintenance task.当我尝试创建维护任务时会发生这种情况。 The code for that is also below right here:代码也在下面:

protected void createMaintenance_Click(object sender, System.EventArgs e)
        {
            string SQLstr;

                if (txtMaintenanceName.Text.Length > 0)
                {
                    if (maintenance_table == "ACTIVE_DAILYMAINTENANCE")
                    {
                        SQLstr = "SELECT TOP(1) MAINTENANCE_ID FROM ACTIVE_DAILYMAINTENANCE WHERE SCHEDULE_DATE = " + value + " ORDER BY MAINTENANCE_ID desc";
                        using (DataTableReader objDataReader = OS.OSFunctions.executeSQLQuery(SQLstr))
                        {
                            if (objDataReader.Read())
                            {
                                int id = Convert.ToInt32(objDataReader["Maintenance_ID"]) + 1;
                                SQLstr = "insert into " + maintenance_table + " (maintenance_id, DAILY_MAINTENANCE, " + key + ", ADMIN_COMMENT) values ('" + id + "',"
                                    + " '" + txtMaintenanceName.Text + "'," + value + ",'" + txtAdminMaintenanceComment.Text + "')";
                                OS.OSFunctions.executeSQLNonQuery(SQLstr);
                            }
                        }
                    }
                    else
                    {
                        SQLstr = "insert into " + maintenance_table + "(DAILY_MAINTENANCE, " + key + ", ADMIN_COMMENT) values ('" + txtMaintenanceName.Text + "'," + value + ",'" + txtAdminMaintenanceComment.Text + "')";
                        OS.OSFunctions.executeSQLNonQuery(SQLstr);
                    }
        }

Again, it is the getMaintenance() method giving me the error.同样,是 getMaintenance() 方法给了我错误。 This also isn't all my code, I do call the getMaintenance() function sometime later in the code for CreateMaintenance.这也不是我的全部代码,我稍后会在 CreateMaintenance 的代码中调用 getMaintenance() function。 Any help would be greatly appreciated.任何帮助将不胜感激。

EDIT: CODE TRYING OUT DATA SET编辑:代码尝试数据集

private DataSet getMaintenance()
{
   DataSet maintenance_ds = new DataSet();
            string SQLstr= "SELECT MAINTENANCE_ID,DAILY_MAINTENANCE,ADMIN_COMMENT FROM " + maintenance_table + " where " + key + " like " + value + " order by MAINTENANCE_ID ";
            using(SqlConnection connection=new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
            {
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = new SqlCommand(SQLstr, connection);
                adapter.Fill(maintenance_ds);
                return maintenance_ds;
            }
}

So, you execute所以,你执行

DataTableReader objDataReader = OS.OSFunctions.executeSQLQuery(SQLstr)

in your using .在您using . SQLstr is SQLstr

"SELECT MAINTENANCE_ID,DAILY_MAINTENANCE,ADMIN_COMMENT FROM " + maintenance_table + " where " + key + " like " + value + " order by MAINTENANCE_ID ";

You will need to use a debugger and jump to this line just before the error is thrown.您将需要使用调试器并在引发错误之前跳转到该行。 First of all, you will need to find out what maintenance_table , key and value is.首先,您需要找出maintenance_tablekeyvalue是什么。 Try finding out what the generated query is and run it in your RDBMS, I think it will most likely return a null for some reason.尝试找出生成的查询是什么并在您的 RDBMS 中运行它,我认为它很可能由于某种原因返回null

It is possible that you are just missing a wildcard character of % being wrapped around value if you have the intention to have a "contains" rather than an "equals" check.如果您打算进行“包含”而不是“ value ”检查,则可能只是缺少%的通配符。

Anyway, in order to detect what the error is you will need to find out what is being generated and why your query results in a null .无论如何,为了检测错误是什么,您需要找出正在生成的内容以及为什么您的查询会导致null Once you know what the problem is, you will also know what you need to fix, which largely simplifies the problem.一旦你知道问题是什么,你也会知道你需要修复什么,这在很大程度上简化了问题。

Since you do not use a parameterized query, I have to mention that if any of the dynamic values you concatenate to the query may come from untrusted sources, such as user input, then your query is vulnerable to SQL injection and you will need to protect your project against this potential exploit.由于您不使用参数化查询,我不得不提一下,如果您连接到查询的任何动态值可能来自不受信任的来源,例如用户输入,那么您的查询很容易受到SQL 注入,您需要保护你的项目反对这个潜在的利用。

You do realize that you can send the sql to a datatable, and the columns and the data table is created for you.您确实意识到可以将 sql 发送到数据表,并为您创建列和数据表。

so, use this code to get/return a data table.因此,使用此代码获取/返回数据表。

It not clear if you "else" is to update a existing row, or insert a new one, but the code can look somthing like this:不清楚您“其他”是要更新现有行还是插入新行,但代码可能看起来像这样:

  protected void createMaintenance_Click(object sender, System.EventArgs e)
    {
        DateTime value = DateTime.Today;
        string maintenance_table = "";
        string SQLstr = "";
        string key = "";

        if (txtMaintenanceName.Text.Length > 0)
        {

            if (maintenance_table == "ACTIVE_DAILYMAINTENANCE")
            {
                // add new row
                int id = NextMaintID(value);
                string strSQL = @"SELECT * FROM " + maintenance_table + " WHERE Maintenance_ID = 0";
                DataTable rstSched = MyRst(strSQL);
                DataRow MyNewRow = rstSched.NewRow();

                MyNewRow["maintenance_id"] = id;
                MyNewRow["DAILY_MAINTENANCE"] = txtMaintenanceName.Text;
                MyNewRow["ADMIN_COMMENT"] = txtAdminMaintenanceComment.Text;
                rstSched.Rows.Add(MyNewRow);
                MyUpdate(rstSched, strSQL);
            }
        }
        else
        {
            // update (or add to daily?????
            string strSQL = @"SELECT * FROM " + maintenance_table + " WHERE Maintenance_ID = " + key;
            DataTable rstSched = MyRst(strSQL);
            DataRow MyRow = rstSched.Rows[0];
            MyRow["DAILY_MAINTENANCE"] = txtMaintenanceName.Text;
            MyRow["ADMIN_COMMENT"] = txtAdminMaintenanceComment.Text;
            MyUpdate(rstSched, strSQL);
        }
    }

So, I only need a few helper routines - (make them global in a static class - you can then use it everywhere - saves boatloads of code.所以,我只需要一些辅助例程 - (在 static class 中将它们设为全局 - 然后你可以在任何地方使用它 - 节省大量代码。

so these were used:所以使用了这些:

    public DataTable MyRst(string strSQL)
    {
        // return data table based on sql
        DataTable rstData = new DataTable();
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                cmdSQL.Connection.Open();
                rstData.Load(cmdSQL.ExecuteReader());
            }
        }
        return rstData;
    }


    public DataTable MyRstP(SqlCommand cmdSQL)
    {
        // return data table based on sql command (for parmaters)
        DataTable rstData = new DataTable();
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (cmdSQL)
            {
                cmdSQL.Connection = conn;
                conn.Open();
                rstData.Load(cmdSQL.ExecuteReader());
            }
        }
        return rstData;
    }

    void  MyUpdate(DataTable rstData, string strSQL)
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
                SqlCommandBuilder daU = new SqlCommandBuilder(da);
                da.Update(rstData);
            }
        }
    }

and of course this:当然还有这个:

    int NextMaintID (DateTime value)
    {
        int result = 0;
        string SQLstr = @"SELECT TOP(1) MAINTENANCE_ID FROM ACTIVE_DAILYMAINTENANCE 
                        WHERE SCHEDULE_DATE = @scDate ORDER BY MAINTENANCE_ID desc";
        SqlCommand cmdSQL = new SqlCommand(SQLstr);
        cmdSQL.Parameters.Add("@scDate", SqlDbType.Date).Value = value;

        DataTable rstNextID = MyRstP(cmdSQL);
        result = ((int)rstNextID.Rows[0]["Maintenance_ID"]) + 1;

        return result;

    }

So, how do you eat a elephant?那么,你怎么吃大象呢? Answer: One bite at a time!!!答:一口一口!!!

So, break out just a "few" helper routines that allows data operations against a data table object.因此,只分解“少数”帮助程序例程,允许对数据表 object 进行数据操作。 That update command will work with edits, adds to rows, and even delete row method of a single row.该更新命令将适用于编辑、添加到行,甚至删除单行的行方法。 All such updates can be thus be done with ONE simple update command.因此,所有此类更新都可以通过一个简单的更新命令来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM