Why am i getting connection error to database in asp.net? - asp.net

I am trying the following code:
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
for (int i = 0; i < studList.Rows.Count; i++)
{
//string a = ((DropDownList)studList.Rows[i].FindControl("actionmenu")).SelectedValue;
string grade = ((DropDownList)studList.Rows[i].FindControl("actionmenu")).SelectedValue;
string studentID = studList.Rows[i].Cells[1].Text;
string courseNumber = MyGlobals.selectedCourse.Substring(MyGlobals.selectedCourse.Length-3);
string courseCode = MyGlobals.selectedCourse.Substring(0, MyGlobals.selectedCourse.Length - 3);
SqlCommand com = new SqlCommand("update RegisterTable set Grade=#grade where StudentID=#studentID and CourseCode=#courseCode and CourseNumber=#courseNumber", con);
com.Parameters.AddWithValue("#grade", grade);
com.Parameters.AddWithValue("#studentID", studentID);
com.Parameters.AddWithValue("#courseCode", courseCode);
com.Parameters.AddWithValue("#courseNumber", courseNumber);
com.ExecuteNonQuery();
try
{
SqlDataAdapter da2 = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(c, MyGlobals.student);
MyGlobals.student.dropCourse(reg);
}
catch (Exception) { }
con.Close();
Even though i open the database connection, it gives an error saying that ExecuteNonQuery requires an open and available Connection. The connection's current state is closed. Why is that the case can anyone see?
Thanks

You're closing the connection inside the for-loop, so on the second iteration, the connection isn't open. It should look like this:
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
for (int i = 0; i < studList.Rows.Count; i++)
{
...
SqlCommand com = new SqlCommand(..., con);
...
com.ExecuteNonQuery();
try
{
...
}
catch (Exception) { }
}
con.Close();

You're closing the connection in the loop, so it would move on to the second iteration and the connection would be closed.

Related

Connecting MS_SQL DB IN asp.net

I was trying to connectMs_sql database in asp.net but server error of network path not found... it is not able to establish connection to sql server...comes while in gridview it is taking it as sqldatasource perfectly
This for customized class to call the ADO.Net. Please use this and let me know if you have any doubts.
public class DbConnectionHelper {
public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
string connString = # "your connection string here";
//Object Declaration
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
try {
//Get Connection string and Make Connection
con.ConnectionString = connString; //Get the Connection String
if (con.State == ConnectionState.Closed) {
con.Open(); //Connection Open
}
if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Query;
if (p.Length > 0) // If Any parameter is there means, we need to add.
{
for (int i = 0; i < p.Length; i++) {
cmd.Parameters.Add(p[i]);
}
}
}
if (cmdText == CommandType.Text) // Type : Text
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
if (cmdText == CommandType.TableDirect) //Type: Table Direct
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
cmd.Connection = con; //Get Connection in Command
sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
con.Close(); //Connection Close
} catch (Exception ex) {
throw ex; //Here you need to handle Exception
}
return ds;
}
}

Using datareader to count Asp.net

I'm checking if a barcode from a database table(using a select query) exists and insert the details into another database table else the barcode does not exist. The inserts fine but I would like to count the number of barcodes entered. Say within a session an user enters 5 barcodes then the total count is 5 but my code keeps returning 1 and not incrementing.
protected void btnReturn_Click(object sender, EventArgs e)
{
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString());
//commands identifying the stored procedure
SqlCommand cmd = new SqlCommand("selectCrate", conn);
SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con);
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows) {
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode);
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter = counter + 1;
}
reader.Close();
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
You can store the number in session then do something with it when the session ends (store it in a database or whatever you want). Declare a session variable:
Session[“NumInserts”] = 0;
Then update it with each insert:
Session[“NumInserts”] = (int) Session[“NumInserts”] + 1;
That variable will be maintained as long as the session exists. Also, make sure you only declare the session variable once and don’t ever allow it to reset during the session’s life cycle. Otherwise, it will go back to 0 and give you inaccurate results.
i rechecked to make sure and i misunderstood your question which led to some confusion.
And to answer your question i don't think there is any easy solution to update realtime the numbers. Any solution of i can think of is websocket connection which I personally have no knowledge of inside webforms(Don't even know if its possible).
I formatted your code. This should give you the total rows back in one go(no realtime update on screen).
protected void btnReturn_Click(object sender, EventArgs e)
{
int counter = 0;
string barcode = txtBarcode.Text;
string location = lblLocation.Text;
string user = lblUsername.Text;
string actType = lblAct.Text;
string date = lblDate.Text;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString()))
{
con.Open();
//commands identifying the stored procedure
using (SqlCommand cmd = new SqlCommand("selectCrate", con))
{
using (SqlCommand cmd1 = new SqlCommand("CreateCrateBox", con))
{
// execute the stored procedures
cmd.CommandType = CommandType.StoredProcedure;
cmd1.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#crateno", barcode));
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
lblResult.Text = reader[0].ToString();
lblResult1.Text = reader[1].ToString();
cmd1.Parameters.Add("#crateno", SqlDbType.NVarChar).Value = barcode;
cmd1.Parameters.Add("#CurrentLocation", SqlDbType.NVarChar).Value = location;
cmd1.Parameters.Add("#Username", SqlDbType.NVarChar).Value = user;
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = date;
cmd1.Parameters.Add("#status", SqlDbType.NVarChar).Value = actType;
counter++;
}
cmd1.ExecuteNonQuery();
txtCount.Text = counter.ToString();
lblCount.Text = string.Format("Number of rows: {0}", counter);
}
else
{
lblError.Text = barcode + " does not exist!!";
}
}
}
}
}
}

How to read uncommited transaction within sqltransaction?

i got a problem when using SQLTransaction in my .net framework 2.0 c# code
this is my code:
public bool register()
{
SqlConnection conn = DB.getInstance().getConnection();
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Transaction = sqlTransaction;
try
{
cmd = insertMembers(cmd);
cmd.ExecuteNonQuery();
SqlDataReader read = null;
cmd.CommandText = "SELECT * FROM members WHERE username='" + username + "'";
read = cmd.ExecuteReader();
while (read.HasRows)
{
id0 = (int)read["id0"];
}
cmd = insertMembersBalance(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersEPoint(cmd);
cmd.ExecuteNonQuery();
cmd = insertMembersVerify(cmd);
cmd.ExecuteNonQuery();
reset();
sqlTransaction.Commit();
}
catch(Exception e)
{
sqlTransaction.Rollback();
Console.WriteLine(e.ToString());
return false;
}
finally
{
conn.Close();
}
return true;
}
I can't get the id from members table to use for insert another records into another table.
is there any other solution?
You must call dr.Read() first than SqlDataReader dr = cmd.........
if (read.HasRows) // needs to be if not while or it will just loop
{
read.Read();
id0 = (int)read["id0"];
}
read.Close(); // need to close the reader before you can use the cmd
if you want to loop through all rows then
while (read.Read())
{
id0 = (int)read["id0"];
}

i want to use data reader & update statement at same time

here is code
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
mon = mon - 1; //because month array is with 0
Label1.Text = day.ToString();
if (day==21)
{
int j = 1;
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = MyConn;
cmd1.CommandText = "SELECT No_of_times,Dustbin_no from mounthly_data";
SqlDataReader MyReader = cmd1.ExecuteReader();
while (MyReader.Read())
{
String a = MyReader["No_of_times"].ToString();
String b = MyReader["Dustbin_no"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set [" + month[mon] + "]='"+a+"' where Dustbin_no='"+b+"'"; //just see ["+month[mon+"] it's imp
i = cmd.ExecuteNonQuery();
}
MyReader.Close();
}
i got error as
There is already an open DataReader associated with this Command which must be closed first.
I think you should give us the rest of the code above this code block because I'm not sure how a ExecuteNonQuery is using up a datareader. But from what I can gather, what you probably want is to open two separate connections. Only one datareader can be open per connection at a time. Either you use two separate connections or you could maybe use a datatable/dataset for the result of both your queries.
EDIT: From the rest of your code, yes, using two connections would be the simplest answer. When a reader is open, the connection associated with it is dedicated to the command that is used, thus no other command can use that connection.
I would recommend using a DataTable as this OLEDB example shows:
public static void TrySomethingLikeThis()
{
try
{
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = Users.GetConnectionString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.AsEnumerable())
{
cmd.CommandText = "UPDATE Customers SET CustomerName='Ronnie' WHERE ID = 4";
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

how to write select parameterized query in asp.net

Below code is written to call parameterized select query in asp.net
public bool checkConflictTime()
{
bool TimeExists = false;
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE starttime= #starttime AND endtime = #endtime";
SqlCommand sqlcommand = new SqlCommand(sql,sqlconn);
//sqlcommand.Connection = sqlconn;
//string sql = "CheckConflictTimings";
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));
sqlcommand.Parameters.Add(new SqlParameter("#endtime", ddlEndTime.SelectedItem.Text));
SqlDataAdapter da = new SqlDataAdapter(sql, sqlconn);
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TimeExists = true;
}
}
catch (Exception ex)
{
}
finally
{
sqlconn.Close();
sqlconn.Dispose();
}
return TimeExists;
}
Is there something wrong? it threw error of :Must declare the scalar variable "#starttime"
when filling data adapter.
Try
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
Try
sqlcommand.Parameters.Add(new SqlParameter("starttime", ddlStartTime.SelectedItem.Text));
I don't think you need the # prefix when adding the parameter.
I think you're not passing your command as a SelectCommand to the adapter.
da.SelectCommand = sqlcommand;
Try
sqlcommand.Parameters.AddWithValue("#starttime",ddlStartTime.SelectedItem.Text);
instead of
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));

Resources