can't retrieve the wanted data out from database - asp.net

I have created an ASP.NET application in Visual Studio 2010. I am having trouble in retrieving the data i wanted from the two dates i selected from the date picker. once i select the 2 dates, it just keep displaying all the data out and not the dates that i have selected.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
string startdate = (string)Session["startdate"];
string enddate = (string)Session["enddate"];
DateTime one = Convert.ToDateTime(startdate);
DateTime two = Convert.ToDateTime(enddate);
if (DateTime.Compare(two, one)>=0)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True");
conn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN '" + startdate + "' AND '" + enddate + "')", conn);
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.Visible = true;
GridView1.DataBind();
conn.Close();
}
else
{
GridView1.Visible = false;
string strMsg = " Data not found for the choosen dates.";
Response.Write("<script>alert('" + strMsg + "')</script>");
}
}

My initial observation is that there is a ) in your SQL with no matching ( - I wonder if your command is simply throwing an exception...?
The first thing I would try is parameterizing it; in addition to being a really really good idea anyway, it could avoid formatting (dd/MM vs MM/dd) issues in the dates:
if(two >= one)
{
DataSet ds = new DataSet();
using(var conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True"))
using(var sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN #start AND #end", conn))
using(var da = new SqlDataAdapter(sqlcmd))
{
sqlcmd.Parameters.AddWithValue("start", one);
sqlcmd.Parameters.AddWithValue("end", two);
conn.Open();
da.Fill(ds);
}
}

using(SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True"))
{
conn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN #startDate AND #endDate", conn);
sqlcmd.Parameters.AddWithValue("startDate" <Your start date>);
sqlcmd.Parameters.AddWithValue("endDate" <Your end date>);
...
Also notice the error with parantheses in your command string.

Related

I try to update name record but I can't

protected void submit_Click(object sender, EventArgs e)
{
Label2.Text = Session["id"].ToString();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = con.CreateCommand();
con.Open();
string UpdateQuery = "Update register set name='" + name.Text + "'where email='" + Session["id"] + "'";
SqlCommand cmd3 = new SqlCommand(UpdateQuery, con);
cmd3.CommandType = CommandType.Text;
con.Close();
}
}
I want to update name record using session for user profile in asp.net.
Try like this:
using (SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
{
string strSQL = "UPDATE register set [name] = #name " +
"WHERE email = #email";
using (SqlCommand cmd = new SqlCommand(strSQL, conn))
{
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = name.Text;
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = Session["id"].ToString();
conn.Open();
cmd.ExecuteNonQuery();
}
}
The above will dispose/close the connection for you. And this will even close the connection if you have some error in the code.
The above also removes the messy "'" and concatenation in your code (easy to read, and maintain). And by using parameter's the code is also safe from injection.
hence:

my asp.net web service code is giving error

hello i have created the code for extracting age from table test
but instead of returning the age it is returning me the following statement
System.Data.SqlClient.SqlDataReader
here is the code
[WebMethod]
public string Getcustomername(string name)
{
SqlConnection con = new SqlConnection("Data Source=GURJOT;Initial Catalog=TEST;Integrated Security=True");
SqlCommand com = new SqlCommand();
com.Connection = con;
con.Open();
com.CommandText = "SELECT * from test WHERE Name='" + name + "'";
SqlDataReader dt = com.ExecuteReader();
dt.Read();
con.Close();
dt.Close();
return dt.ToString();
any help would be appreciated
Thanks
Instead of returning dt.ToString() you should return the value of a field:
public string GetCustomerAge(string name)
{
using (SqlConnection con = new SqlConnection("Data Source=GURJOT;Initial Catalog=TEST;Integrated Security=True"))
{
using(SqlCommand com = new SqlCommand())
{
com.Connection = con;
con.Open();
com.CommandText = "SELECT age from test WHERE Name='" + name + "'";
using (SqlDataReader dt = com.ExecuteReader())
{
if (dt.Read())
{
return System.Convert.ToString(dt.GetValue(0));
}
}
}
return "";
}
And please, use parameterized queries - http://en.wikipedia.org/wiki/SQL_injection .

can't retrieve the wanted data out from database and have error in closing connection

I have created an ASP.NET application in Visual Studio 2010. I am having trouble in retrieving the data i wanted from the two dates i selected from the date picker. once i select the 2 dates, it just keep displaying all the data out and not the dates that i have selected and i also have problem closing a connection as it gave me this error : "Adding the specified count to the semaphore would cause it to exceed its maximum count."
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
//getting data
string startdate = (string)(Session["startdate"]);
string enddate = (string)(Session["enddate"]);
DateTime one = Convert.ToDateTime(startdate);
DateTime two = Convert.ToDateTime(enddate);
if (two >= one)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("Data Source="";Integrated Security=True");
conn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN '" + startdate+ "' AND '" + enddate+ "'", conn);
SqlDataReader reader = sqlcmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.Visible = true;
conn.Close();
}
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection("Data Source=MCDU-PC34\\SQLEXPRESS;Initial Catalog=ncpsdbb;Integrated Security=True");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN '" + startdate + "' AND '" + enddate + "'",conn);
SqlDataAdapter da = null;
da.SelectCommand = cmd;
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.Visible = true;
conn.Close();
Supposing your session variables are two correct dates then you should not use string concatenation to pass an sql command to your database but you should use a parameterized query
string cmdText = "SELECT * FROM StudentTransactions " +
"WHERE TimeDate BETWEEN #iniDT AND #endDT"
SqlCommand sqlcmd = new SqlCommand(cmdText, conn);
sqlCmd.Parameters.AddWithValue("#iniDT", one);
sqlCmd.Parameters.AddWithValue("#endDT",two);
This approach will leave the duty to pass in the correct format for the dates to the framework code and you avoid parsing problems and close the door to sql injections attacks.

Why does it throws error like this?

I do import the data from Excel sheet to Sql database..everything is fine,when i run this code,my access engine could not find mt sheet,it throws like this error..
my error is
The Microsoft Jet database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.
but i already checked with my designation folder,its correct..then i don't know why it's repeated
my C# code below..
public partial class _Default : System.Web.UI.Page
{
string constr = #"Data Source=VIS1-B12\SQLEXPRESS;Initial Catalog=Sql_Excel;Integrated Security=True providerName=System.Data.SqlClient" ;
protected void btn_okClick(object sender, EventArgs e)
{
string path = Fup_Excel.PostedFile.FileName;
string exconstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+path+";Extended Properties=Excel 8.0";
OleDbConnection excelcon = new OleDbConnection(exconstr);
excelcon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", excelcon);
OleDbDataReader dbreader;
OleDbDataAdapter dap = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
//dap.Fill(ds,"sheet1");
dbreader = cmd.ExecuteReader();
SqlBulkCopy bcpy = new SqlBulkCopy(constr);
bcpy.DestinationTableName = "Excel_Details";
bcpy.WriteToServer(dbreader);
//GridView1.DataSource = ds.Tables[0].DefaultView;
//GridView1.DataBind();
excelcon.Close();
}
}
It's better you should retrieve excel sheet name using code.
Code is shown below
OleDbConnection con = new OleDbConnection(ConnString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);

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

Resources