i want to use data reader & update statement at same time - asp.net

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

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

The variable name #IdLiquidacion has already been declared. Variable names must be unique within a query batch or stored procedure.'

I have the following problem when inserting the info in the databases
public void Insertar()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=BD-DLLO-SP2016;Initial Catalog=GobernacionCesar;Integrated Security=True";
con.Open();
string query = "INSERT INTO Liquidacion (IdLiquidacion, IdPeriodo, FechaGeneracion, Usuario) VALUES(#IdLiquidacion, #IdPeriodo, #FechaGeneracion, #Usuario)";
SqlCommand com1 = new SqlCommand(query, con);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
com1.Parameters.AddWithValue("#IdLiquidacion", A);
com1.Parameters.AddWithValue("#IdPeriodo", cell);
com1.Parameters.AddWithValue("#FechaGeneracion", DateTime.Now.ToString());
com1.Parameters.AddWithValue("#Usuario", gridRow.Cells[0].Text);
com1.ExecuteNonQuery();
}
con.Close();
return;
}
Move the command
SqlCommand com1 = new SqlCommand(query, con);
to the beginning of the loop:
foreach (GridViewRow gridRow in GridView4.Rows)
{
SqlCommand com1 = new SqlCommand(query, con);
....
}
You should
define the parameters outside of the loop
only set the values for the parameters inside the loop
Like this:
SqlCommand com1 = new SqlCommand(query, con);
// define parameters - you need to adapt the datatypes - I was only guessing
com1.Parameters.Add("#IdLiquidacion", SqlDbType.Int);
com1.Parameters.Add("#IdPeriodo", SqlDbType.VarChar, 50);
com1.Parameters.Add("#FechaGeneracion", SqlDbType.DateTime);
com1.Parameters.Add("#Usuario", SqlDbType.VarChar, 100);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
// inside the loop, only SET the values
com1.Parameters["#IdLiquidacion"].Value = A;
com1.Parameters["#IdPeriodo"].Value = cell;
com1.Parameters["#FechaGeneracion"].Value = DateTime.Now;
com1.Parameters["#Usuario"].Value = gridRow.Cells[0].Text;
com1.ExecuteNonQuery();
}
You're adding the parameters in the loop. If you clear them before adding, this should work.

Why am i getting connection error to database in 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.

Detailsview in ASP.NET

I am trying to hit sql server with objectdatasource and return a datatable to fill my details view control. the selected ID value is returned by a gridview control. It seems like the datatable is not filled by adapter, and i couldn't figure out why. The ID in sql is set as a primary key (Int, 4, not null). The debugger says the Detail datatable is null. Any help is much appreciated.
public DataTable GetDetail(string ID)
{
if (ID == "")
{
return null;
}
else
{
DataTable Detail = null;
using (SqlConnection conn = new SqlConnection(connection))
{
string comm = #"select * from dbo.Products where ID = #ID";
conn.Open();
SqlDataAdapter adapter=null;
using (SqlCommand cmd = new SqlCommand(comm, conn))
{
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = Convert.ToInt32(ID);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(Detail);
return Detail;
}
}
}
I think you missed the commandType
cmd.CommandType = CommandType.Text;
Try this
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connection))
{
string myquery="select * from dbo.Products where ID = #ID";
SqlCommand cmd = new SqlCommand(myquery, con);
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
cmd.Parameters.Add("#ID", SqlDbType.NVarChar, 15).Value = ID;
dap.Fill(ds);
return ds.Tables[0];
}
Thanks for ALL.
The problem is I didnt initialize my datatable to a new instance.
DataTable Detail = null; ===> DataTable Detail = new Datatable();
and also the convert should be done in sql not in codes.
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = ID;
string comm = #"select * from dbo.Products where ID = convert(int,#ID)";

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