SQL Query inserting data into database - asp.net

I am trying to insert date into database from Session DateValue by converting it into dateTime. The problem i am facing is its accepting the value of april month but when i am entering the value of March its giving error.
Please Help, The Query and the code i have used is as follow:
string a = Session["Date_Value"].ToString();
DateTime date= DateTime.Parse(a);
foreach (GridViewRow g1 in grdData.Rows)
{
//string Status = (g1.FindControl("TextBox1") as TextBox).Text;
//int Status = Convert.ToInt32(Sta);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Real_Attendance"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into Attendanc(Stu_id,Status,time,Date,Sub_id) values('" + g1.Cells[3].Text + "',#Status,'" + Session["Time_Value"].ToString() + "', #Date ,'" + Session["Sub_id"].ToString() + "')", con);
//SqlCommand cmd = new SqlCommand("Insert into Attendanc(Stu_id,Status,time,Date,Sub_id) values('" + g1.Cells[3].Text + "','"+ g1.Cells[1].Text +"','" + Session["Time_Value"].ToString() + "','" + Session["Date_Value"].ToString() + "','" + Session["Sub_id"].ToString() + "')", con);
//cmd.Parameters["#Status"].Value = ((Label)(g1.FindControl("Label1"))).Text;
cmd.Parameters.AddWithValue("#Status", ((Label)(g1.FindControl("Label1"))).Text);
cmd.Parameters.AddWithValue("#Date", date.ToShortDateString());
// cmd.Parameters.AddWithValue("#Date", date.ToShortDateString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
This is the code I am using to create session. I am creating session at webform3 And using its value at webform4
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Calendar1.Visible = false;
System.DateTime myDate = new System.DateTime();
myDate = Calendar1.SelectedDate;
txtDate.Text = myDate.ToString("dd/MM/yyyy");
Date = txtDate.Text;
day = Calendar1.SelectedDate.DayOfWeek.ToString();
Response.Write(day);
txtday.Text = day;
Session["Date_Value"] = Date;
//SelectTime();
}

I'm not sure this will solve your problem, but it will improve your code:
string a = Session["Date_Value"].ToString();
DateTime date= DateTime.Parse(a);
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Real_Attendance"].ConnectionString))
{
con.Open();
foreach (GridViewRow g1 in grdData.Rows)
{
using(SqlCommand cmd = new SqlCommand("Insert into Attendanc (Stu_id,Status,time,Date,Sub_id) values (#Stu_id, #Status, #Time, Convert(DateTime, #Date, 103), #Sub_id)", con))
{
cmd.Parameters.AddWithValue("#Stu_id", g1.Cells[3].Text);
cmd.Parameters.AddWithValue("#Status", ((Label)(g1.FindControl("Label1"))).Text);
cmd.Parameters.AddWithValue("#Time", Session["Time_Value"].ToString());
cmd.Parameters.AddWithValue("#Date", date.ToString("dd/MM/yyyy"));
cmd.Parameters.AddWithValue("#Sub_id", Session["Sub_id"].ToString());
cmd.ExecuteNonQuery();
}
}
con.Close();
}
First, I've changed sql statement to have only parameters. It's cleaner, safer, and easier to read and debug this way.
Second, I've changed the value that #Date parameter gets to a specific date format, and informed the database the expected format using the Convert function. this should fix your conversion problem.
Other improvements: I've moved the opening and closing of the connection outside of the foreach loop. there is no need to close and reopen the connection for each command execute. Also, I've moved the SqlConnection and the SqlCommand into using statements, as recommended by microsoft.

Related

Upload and update excel file

I have a task to upload the excel file and also check update if the same record found, I have uploaded the excel file in the database which is working fine.
Now, I have to check if the same records inserted then update otherwise insert the new records, I have two table first I am inserting the records in the temp table then after that I am checking the temp table with the original table , if records matches then update else insert, I am using nested for loop to check the records
my loop works fine and insert the top two records, but when it comes to the 3rd record then insert it multiple times and on 4th again multiple times,Kindly guide me what i am doing wrong
here is my code so far
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
int id;
string contactPerson;
string designation;
string company;
string contact;
string emailaddress;
string city;
string region;
string industry;
string division;
string mobile;
string address;
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/uploadExcel/") + FileUpload1.FileName);
String ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
DeleteRecords();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr[0].ToString() != "")
{
// Response.Write("<br/>"+dr[0].ToString());
id = Convert.ToInt32(dr[0].ToString());
contactPerson = dr[1].ToString();
designation = dr[2].ToString();
company = dr[3].ToString();
emailaddress = dr[4].ToString();
contact = dr[5].ToString();
mobile = dr[6].ToString();
address = dr[7].ToString();
city = dr[8].ToString();
region = dr[9].ToString();
industry = dr[10].ToString();
division = dr[11].ToString();
InsertTemp(id, contactPerson, designation, company, emailaddress, contact,
mobile, address, city, region, industry, division);
//InsertOrignal(id, contactPerson, designation, company, emailaddress, contact,
// mobile, address, city, region, industry, division);
}
else
{
break;
}
String myconn = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection conn = new SqlConnection(myconn);
conn.Open();
DataTable dt_temp = new DataTable();
DataTable dt_orignal = new DataTable();
SqlDataAdapter da_temp = new SqlDataAdapter("select * from Tbl_ExcelData order by id asc", conn);
SqlDataAdapter da_orignal = new SqlDataAdapter("select * from Tbl_ExcelUploadData order by id asc", conn);
da_temp.Fill(dt_temp);
da_orignal.Fill(dt_orignal);
if (dt_orignal.Rows.Count > 0)
{
for (int i = 0; i < dt_temp.Rows.Count; i++)
{
for (int j = 0; j < dt_orignal.Rows.Count; j++)
{
if (dt_temp.Rows[i]["email"].ToString() == dt_orignal.Rows[j]["email"].ToString())
{
//Update Record if required
}
else
{
//insert record into orignal table
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
}
}
else
{
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
lblmessage.Text = "Data Has Been Updated Successfully";
mycon.Close();
File.Delete(ExcelPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void InsertTemp(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address,String city,String region,String industry,
String division)
{
//String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "insert into Tbl_ExcelData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
private void InsertOrignal(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address, String city, String region, String industry,
String division)
{
//String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "insert into Tbl_ExcelUploadData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
private void DeleteRecords()
{
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "Delete from Tbl_ExcelData";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
If you have the Temporary table just to check if the row exists in an Original table, then it is not a good practice.
Directly check if the row exists in your original table with the Primary key id or any Unique Key and then decide whether to Insert or Update.
One way to do this,
while (dr.Read())
{
if (dr[0].ToString() != "")
{
id = Convert.ToInt32(dr[0].ToString()); //add other columns which needs to be fetched from Excel
string query = "select count(1) from Tbl_ExcelData where id=?"; //To check if the row already exsits
SqlCommand cmd = new SqlCommand(con);
cmd.CommandText = query;
cmd.Paramaters.Add(new SqlParameter(1, id));
int count = (Int32) cmd.ExecuteScalar();
if (count > 0) //which means row already exists
{
//Your update code goes here
}
else
{
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
After comments, here is a basic idea. One way you can load your excel data into DataTable and loop through it and decide for Upsert. Remember to learn about MultipleActiveResultSets
try
{
string ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
string _oleDBConnectionString = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended Properties=Excel 8.0; Persist Security Info = False", ExcelPath);
string _sqlConnectionString = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True; MultipleActiveResultSets=true;"; //enable MultipleActiveResultSets as you'll be opening a nested SqlConnection
string _excelQuery = "select * from [Sheet1$]";
DataTable tempDataTable = null;
using (var conn = new OleDbConnection(_oleDBConnectionString)) //This code loads your excel data into data table
{
conn.Open();
using (var cmd = new OleDbCommand(_excelQuery, conn))
{
using (var reader = cmd.ExecuteReader())
{
var dt = new DataTable();
dt.Load(reader); //this will load your excel data into DataTable
tempDataTable = dt;
}
}
}
using(var sqlConn = new SqlConnection(_sqlConnectionString)) //this code will connect to sql db and upsert based on the id from the excel
{
sqlConn.Open();
string countQuery = "select count(1) from Tbl_ExcelData where id=:id";
using(var cmd = new SqlCommand(countQuery, sqlConn))
{
var param = new SqlParameter("#id");
foreach (DataRow row in tempDataTable.Rows) //this will loop through the DataTable rows, the actual rows from Excel which are loaded into DataTable
{
var id = row["id"]; //get the id column from the excel
var contactPerson = row["contactPerson"]; //get the contactPerson column from the excel
cmd.Paramaters["#id"] = id;
int count = (int) cmd.ExecuteScalar();
if (count) //row already exist in original table
{
//update the row in original table
}
else
{
//insert the row in original table
InsertOriginal(sqlConn, id, contactPerson);
}
}
}
}
}
catch(Exception ex)
{
}
function InsertOriginal(SqlConnection conn, int id, string contactPerson)
{
string insertQuery = "insert into Tbl_ExcelUploadData (id,contactpersonn) values('#id','#contactPerson');
using(var cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add(new SqlParameter("#id",id));
cmd.Parameters.Add(new SqlParameter("#contactPerson", contactPerson));
cmd.ExecuteNonQuery();
}
}
Also, this is not a tested code. Feel free to comment back.

Error: An expression of non-boolean type specified in a context where a condition is expected

I want to pass three query string variables, which ars DateFrom, DateTo and UserName. When I call that the variable, it shows an error:
'An expression of non-boolean type specified in a context where a condition is expected, near 'admin'.'".
How can I resolve the issue? Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
strDate = Convert.ToDateTime(Request.QueryString["DateFrom"]);
endDate = Convert.ToDateTime(Request.QueryString["DateTo"]);
UserName = Convert.ToSingle(Request.QueryString["UsName"]);
string UserName = Request.QueryString["UsrName"];
string sql;
sql = ("SELECT * FROM tblReport WHERE Date between'" + strDate + "'and'" + endDate + "'and'" + UserName + "'");
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
DataSet dst = new DataSet();
sda.Fill(dst, "tblReport");
crypt.Load(#"D:\My Project\Asp.Net\ITApplication\ITApplication\CrystalReport.rpt");
crypt.SetDataSource(dst);
CrystalReportViewer1.ReportSource = crypt;
}
you are missing something in your where clause... should be like this:
WHERE Date BETWEEN '<FromDate>' AND '<ToDate>'
AND UserName = '<UserName>'
Your SQL string is not formatted well.
Put spaces near yout and operators and use () in your between:
sql = ("SELECT * FROM tblReport WHERE [Date] between ('" + strDate + "' and '" + endDate + "') and UserName='" + UserName + "'");
Side note:
Using SQL strings with concatenating values like this is a very bad idea. It exposes you to SQL Injections, and overall a bad practice. Please consider using Command.Parameters:
SqlCommand Command = new SqlCommand("SELECT * FROM tblReport WHERE [Date] between (#strDate and #endDate) and UserName=#UserName");
Command.Parameters.Add(new SqlParameter("strDate", strDate));
Command.Parameters.Add(new SqlParameter("endDate", endDate));
Command.Parameters.Add(new SqlParameter("UserName", UserName));

ASP.NET , SqlDataReader and SqlCommand (There is already an open DataReader associated with this Command which must be closed first)

I'm getting this error:
There is already an open DataReader associated with this Command which must be closed first.
I don't know where is the problem. It's closed but still says it's open. Please help!
The first command is to get all employees that have vacation between two dates.
The second command I am using it to retrieve dates by ID.
Here is my code:
using (SqlConnection con = new SqlConnection(connection))
{
con.Open();
SqlCommand cmd = new SqlCommand(" SELECT distinct E.EmployeeId, E.FirstName FROM Employee E INNER JOIN Vacation V ON E.EmployeeId = V.EmployeeId " +
" WHERE ((V.Dates >= #Start AND V.Dates <= #End) ) ", con);
cmd.Parameters.AddWithValue("#Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd.Parameters.AddWithValue("#End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Response.Write((dr[1]).ToString() + " "); // Check if retrieves employee name
// Now by Id I want to get all dates belong to specific employee
SqlCommand cmd2 = new SqlCommand("SELECT V.Dates FROM Vacation V " +
" WHERE ((V.Dates >= #Start AND V.Dates <= #End) ) ", con);
cmd2.Parameters.AddWithValue("#Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("#End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("#EmployeeId", Convert.ToInt32(dr[0]));
using (SqlDataReader dr2 = cmd2.ExecuteReader())
{
while (dr2.Read())
{
Response.Write(Convert.ToDateTime(dr2[0]));
}
}
Response.Write("<br/>");
}
GridView7.DataSource = cmd.ExecuteReader();
GridView7.DataBind();
}
con.close();
}
Add this to your connection string:
MultipleActiveResultSets=True

Fetching Data from database as per details

string date = ddlShowDates.SelectedValue.ToString();
cmd = new SqlCommand("SELECT tbl_Shows.ShowTime FROM tbl_Shows INNER JOIN tbl_MovieTimings ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId WHERE tbl_MovieTimings.Date='" + date + "'", con);
I want to display show time in dropdownlist as per date is selected.
Always use sql-parameters instead of string concatenation to prevent sql-injection.
I guess you have a second DropDownList which should be filled from the first:
DateTime date = DateTime.Parse(ddlShowDates.SelectedValue);
string sql = #"SELECT tbl_Shows.ShowTime
FROM tbl_Shows
INNER JOIN tbl_MovieTimings
ON tbl_Shows.ShowId = tbl_MovieTimings.ShowId
WHERE tbl_MovieTimings.Date=#Date";
using(var con = new SqlConnection("ConnectionString"))
using(var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add("#Date", SqlDbType.Date).Value = date;
con.Open();
using(var rd = cmd.ExecuteReader())
{
while(rd.Read())
{
TimeSpan time = rd.GetTimeSpan(0);
timeDropDownList.Items.Add(time.ToString());// change format as desired in TimeSpan.ToString
}
}
}

Conversion failed when converting datetime from character string ASP.NET

I get a Conversion failed error when converting DateTime from character string, any help?
sqlcon.Open();
sqlcmd = new SqlCommand("select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] from emp where MyDate between '" + TextBoxData1 + "' and '" + TextBoxData2 + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
GridViewRodyti.DataSource = dt;
GridViewRodyti.DataBind();
sqlcon.Close();
This has got SQL Injection written all over it...
Use parameterized queries e.g.
var sqlCmd = new SqlCommand("select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] from emp where MyDate between '#startDate' and '#endDate'", sqlcon);
sqlCmd.Parameters.Add(new SqlParameter("#startDate", DateTime.Parse(TextBoxData1)));
sqlCmd.Parameters.Add(new SqlParameter("#endDate", DateTime.Parse(TextBoxData2)));
Your issue is probably due to an invalid date format, if you use SqlParameter and convert the string to a DateTime it should take care of the conversion for you.
I would advise you do it like this...
sqlcon.Open();
DateTime date1;
DateTime date2;
DateTime.TryParse(TextBoxData1.Text, out date1); //is TextBoxData1 a TextBox?
DateTime.TryParse(TextBoxData2.Text, out date2);
if (date1 != null && date2 != null) {
sqlcmd = new SqlCommand(
"select [Uzsak_Nr],[Preke],[Uzsak_Kiekis],[Gaut_Kiekis],[MyDate],[Gaut_Data] " +
"from emp where MyDate between #dt1 and #dt2 ", sqlcon);
sqlcmd.Parameters.AddWithValue("#dt1", date1);
sqlcmd.Parameters.AddWithValue("#dt2", date2);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
GridViewRodyti.DataSource = dt;
GridViewRodyti.DataBind();
sqlcon.Close();
}
Using parameterised queries is much nicer and doesn't run the risk of injection.
I have assumed you are using SQLServer.

Resources