Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;

namespace DBTools {
    public class DBUtility {
        private static string connString = "Data Source=MK;Initial Catalog=students;Integrated Security=True";

        public static SqlDataReader ExecuteSelect(string cmdName, CommandType cmdType, params SqlParameter[] pars) {
            SqlDataReader reader = null;
            using (SqlConnection conn = new SqlConnection(connString)) {
                using (SqlCommand cmd = conn.CreateCommand()) {
                    cmd.CommandType = cmdType;
                    cmd.CommandText = cmdName;
                    if (pars.Length > 0) {
                        cmd.Parameters.AddRange(pars);
                    }
                    conn.Open();
                    reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    return reader;
                }
            }

        }

        public static Int32 ExecuteNonQuery(string cmdName, CommandType cmdType, params SqlParameter[] pars) {
            using (SqlConnection conn = new SqlConnection(connString)) {
                using (SqlCommand cmd = new SqlCommand(cmdName, conn)) {
                    // There're three command types: StoredProcedure, Text, TableDirect. The TableDirect
                    // type is only for OLE DB.
                    cmd.CommandType = cmdType;
                    if (pars.Length > 0)
                        cmd.Parameters.AddRange(pars);

                    conn.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }
    }
}



The reader object in the method above 'ExecuteSelect' method (on tracing the execution) shows that it contains a valid reference. But when I receive the vale in another file for displaying the data, as in the statement below, it shows a null reference that has not been initialized:
SqlDataReader reader = DBUtility.ExecuteSelect("SELECT * FROM stud_master WHERE StudId = @ID", CommandType.Text, new SqlParameter[] { new SqlParameter("@ID", studId) } );
Posted
Updated 8-Oct-15 3:31am
v3
Comments
Sreekanth Mothukuru 8-Oct-15 8:06am    
If it is OK then what do you want to fix and why?
Nathan Minier 8-Oct-15 8:28am    
With Integrated Security it will use the execution context unless you're executing in an impersonated context, but I don't see any evidence of that.

Since you're using System.Web you must have an app pool. Does that App pool identity have permissions on the database server?
Mudit Khetan 8-Oct-15 9:26am    
I am a newbie and trying to learn things. So I do not get yor description. It is working fine when i changed the code to use DataTable. the updated code is given below:
<pre>
DataTable table = DBUtility.ExecuteSelectTable("SELECT * FROM stud_master WHERE StudId = @ID", CommandType.Text, new SqlParameter[] { new SqlParameter("@ID", studId) });
</pre>
ZurdoDev 8-Oct-15 8:33am    
It's not a good idea to pass Readers around. But what exactly is your question?
Mudit Khetan 8-Oct-15 9:30am    
The basic premise of a return vale from a method call is to allow the caller reference be updated with the object sent as return value.
For example:

class Sample{
...
}
someMethod(){
Sample ref = methodReturningSampleObject();
}

If assuming the method methodReturningSampleObject() does not return a null reference at all, then why is my ref null in the code above?

1 solution

Another problem related to the ExecuteNonQuery() method of the above DBUtility class.
In the code below, i have two methods - btnUpdate_Click() and btnInsert_Click() - both doing almost same work, except that one uses and SQl "UPDATE" statement while the latter uses the "INSERT" sql.
Not the funny part is, code for INSERT executes and its data is reflected in the DB. The Code for UPDATE also executes, it returns that one row was affected by the statement, but the changes do not reflect in the DB at all.
protected void btnUpdate_Click(object sender, EventArgs e) {		
	string updateCommand = "UPDATE stud_master SET firstName = @Fname, lastName = @Lname, emailId = @Email, city = @City WHERE StudID = @ID";
	SqlParameter[] parameters = new SqlParameter[] {
		new SqlParameter("@ID", txtID.Text),
		new SqlParameter("@Fname", txtFName.Text),
		new SqlParameter("@Lname", txtLName.Text),
		new SqlParameter("@Email", txtEmail.Text),
		new SqlParameter("@City", txtCity.Text)
	};

	DBUtility dbUtility = new DBUtility();
	if (DBUtility.ExecuteNonQuery(updateCommand, CommandType.Text, parameters) > 0) {
		lblStatus.Text = "Record Successfully Updated.";
	}
	else {
		lblStatus.Text = "Cannot add new Record. Operation failed.";
	}
}

protected void btnInsert_Click(object sender, EventArgs e) {
	string insertCommand = "INSERT INTO stud_master VALUES(@ID, @Fname, @Lname, @Email, @City)";
	SqlParameter[] parameters = new SqlParameter[] {
		new SqlParameter("@ID", txtID.Text),
		new SqlParameter("@Fname", txtFName.Text),
		new SqlParameter("@Lname", txtLName.Text),
		new SqlParameter("@Email", txtEmail.Text),
		new SqlParameter("@City", txtCity.Text)
	};

	Int32 rowsAffected = dbUtility.ExecuteNonQuery(insertCommand, CommandType.Text, parameters);
	if (rowsAffected > 0) {
		lblStatus.Text = "Record Successfully added.";
	}
	else {
		lblStatus.Text = "Cannot add new Record. Operation failed.";
	}
}
 
Share this answer
 
v2
Comments
Richard Deeming 8-Oct-15 14:34pm    
This is not a solution to your question. Why have you posted it as a new solution, and accepted it as the answer?
Mudit Khetan 8-Oct-15 23:45pm    
Sorry, for posting it as a solution, as I mentioned it earlier as well. I wanted to show some additional code, but in the comments section the formatting was not OK. Actually I am new to this forum and would improve with your help and guidance. I must have mistakenly accepted it as solution, which i have now rejected.
Can you please look at the problem i mentioned above and provide solution to it? Thanks in advance.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900