Troubles when fetching data from table with a query with a parameter - asp.net

I'm working with ASP.net. I'm trying to fetch data from a table "Pret" and display them in view. The following code is working properly:
public ActionResult Details(int id)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(chaineConnexion))
{
DataTable tabRetard = new DataTable();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter();
SqlCommand command = new SqlCommand(
"SELECT Livre.titre,Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id", con);
adp.SelectCommand = command;
adp.Fill(tabRetard);
return View(tabRetard);
}
}
Now I'm trying to add a parameter to the query like that, but it throws an exception
System.Data.SqlClient.SqlException : 'Incorrect syntax near 'Retard'
I can't figure out what the problem is !
public ActionResult Details(int id)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(chaineConnexion))
{
DataTable tabRetard = new DataTable();
con.Open();
SqlDataAdapter adp = new SqlDataAdapter();
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id" +
"WHERE Retard.Id_membre = #Id_membre", con);
command.Parameters.AddWithValue("#Id_membre", id);
adp.SelectCommand = command;
adp.Fill(tabRetard);
return View(tabRetard);
}
}

This is caused by a typo in your string concatenation, it's missing whitespace between Membre.Id and WHERE:
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id" + /*Needs a space at the end*/
/*or at the beginning*/ "WHERE Retard.Id_membre = #Id_membre", con);
Try this instead:
SqlCommand command = new SqlCommand(
"SELECT Livre.titre, Membre.nom, " +
"FORMAT(Retard.DatePret, 'yyyy-MM-dd') as DatePret, Nbjour FROM Retard " +
"LEFT JOIN Livre ON Retard.Id_livre = Livre.Id " +
"LEFT JOIN Membre ON Retard.Id_membre = Membre.Id " +
"WHERE Retard.Id_membre = #Id_membre", con);
Also, try to avoid use of AddWithValue since it can often cause problems with query parameters such as incorrect type conversion, query plan cache bloat and so on:
command.Parameters.AddWithValue("#Id_membre", id);
Prefer to use SqlCommand's Parameters.Add methods that include the SqlDbType and length parameters, e.g. for int values:
command.Parameters.Add("#Id_membre", SqlDbType.Int).Value = id;
For string values match the length of the related table/view columns, e.g.:
command.Parameters.Add("#nom", SqlDbType.NVarChar, 50).Value = nom;
Interesting reading on AddWithValue:
Can we stop using AddWithValue() already?
AddWithValue is Evil

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.

is this code vulnerable to SQL Injections?

page loads you have to fill some text boxes and then click add:
tbSpyReports spyReport = new tbSpyReports();
spyReport.sgCityLevel = Convert.ToInt32(tbCityLevel.Text);
spyReport.sgCityName = tbCityName_insert.Text;
....
spyReport.insert();
Response.Redirect(Request.RawUrl);
SqlConnection con = ikaConn.getConn();
SqlCommand command = new SqlCommand("INSERT INTO spyReports(cityName, playerName, cityId, islandId, cordX, cordY, " + "cityLevel, cityWall, cityWarehouse, Wood, Wine, Marble, Crystal, Sulfur, hasArmies) VALUES(" + "#cityName, #playerName, #cityId, #islandId, #cordX, #cordY, " + "#cityLevel, #cityWall, #cityWarehouse, #Wood, #Wine, #Marble, #Crystal, #Sulfur, #hasArmies)", con);
command.Parameters.Add(new SqlParameter("cityName", this.cityName));
command.Parameters.Add(new SqlParameter("playerName", this.playerName));
....
command.ExecuteNonQuery();
command.Dispose();
It shouldn't be vulnerable to traditional SQL injection of this form:
statement = "SELECT * FROM users WHERE name ='" + userName + "';"
as you're using parameterized queries.

Confused about database select query

I am following a session tutorial .The problem is this part.
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME'" +
txtad.Text + "' and YPASS'" + txtpass.Text + "' ",
con);
At this part I am getting an exception named Incorrect syntax -Missing operator(I have tried to translate)
this is the rest of code
OleDbConnection con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+
Server.MapPath("App_Data\\db.accdb"));
con.Open();
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME'" +
txtad.Text + "' and YPASS'" + txtpass.Text + "' ",
con);
OleDbDataReader dr=fecth.ExecuteReader();
if(dr.Read()){
Session.Add("value",txtad.Text);
Response.Redirect("Default.aspx");
You need an equals operator.
OleDbCommand fecth = new OleDbCommand(
"SELECT * FROM YONETICI Where YNAME = '" +
txtad.Text +
"' and YPASS = '" +
txtpass.Text + "' ",
con);
Try that. I added two equals operators to your query.
exactly,you need to add 2 equal sign but i prefer to write your query in a better way
,this one will replace the #Parameter with the value like code below with
fetch.Parameters.addWithValue()
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+Server.MapPath("App_Data\\db.accdb"));
con.Open();
OleDbCommand fecth = new OleDbCommand("SELECT * FROM YONETICI Where YNAME='#txtad' and YPASS='#txtpass'", con);
fecth.Parameters.AddWithValue("#txtad",txtad.Text);
fecth.Parameters.AddWithValue("#txtpass",txtpass.Text);
OleDbDataReader dr=fecth.ExecuteReader();
if(dr.Read()){
Session.Add("value",txtad.Text);
Response.Redirect("Default.aspx");

error : Cannot find table 0

con.Open();
SqlDataAdapter da4 = new SqlDataAdapter("select * from tblbooking where bookid =(select max(bookid) from tblbooking)", con);
DataSet ds4 = new DataSet();
pay = ds4.Tables[0].Rows[0]["costoftickets"].ToString();
Label4.Text = "Amount to Pay : " + pay + " INR.";
da4.Fill(ds4);
DetailsView1.DataSource = ds4;
DetailsView1.DataBind();
con.Close();
You have not filled the DataSet before accessing its contents, so naturally there's no data in it.
con.Open();
SqlDataAdapter da4 = new SqlDataAdapter("select * from tblbooking where bookid =(select max(bookid) from tblbooking)", con);
DataSet ds4 = new DataSet();
da4.Fill(ds4); // this needs to go before accessing the data
pay = ds4.Tables[0].Rows[0]["costoftickets"].ToString();
Label4.Text = "Amount to Pay : " + pay + " INR.";
DetailsView1.DataSource = ds4;
DetailsView1.DataBind();
con.Close();
Note that you still might get errors if your query returns no data.

Populating a drop down list dynamically in ASP.net, and passing that value to another query?

2 questions for everybody.
1) How can I order the years by their value, it crashes when I use DESC?
2) If I populate my list like so:
string strConn = ConfigurationManager.ConnectionStrings["rde_410978ConnectionString"].ToString();
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales DESC"; //DESC DOESNT WORK?
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
How can I make the year selected appear under ddItems.SelectedItem?
WHERE Year = " + ddItems.SelectedItem + "GROUP BY Name ";
That part of another query doesn't work when I populate my list dynamically, any reasons why/ how can I fix it.
Regards.
EDIT:
To make my second question clearer, after debugging its always selecting the top item in the drop down list not the actual selected item?
First, in your sql you are missing "order by"...use this
"Select Distinct Year from MonthlySales order by Year DESC"
Second, you need to make use of the SelectedValue property to get your dropdown's selected value...as below...
WHERE Year = " + ddItems.SelectedValue + " GROUP BY Name";
Having said that, I strongly recommend you to use..."parameterized" sql...Here is an example on how you could enable parameterized sql query...
Give me parameterized SQL, or give me death
Update:
Looks like you are binding your dropdown on every post back...you may try this...
if (!Page.IsPostBack && objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
Ans 1)
cmd.CommandText = "Select Distinct Year from MonthlySales ORDER BY 1 DESC"
You are missing order by. Here it is.
"Select Distinct Year from MonthlySales order by Year DESC";
For your second part you can do this. Please mind the space in " GROUP BY Name"
WHERE Year = " + ddItems.SelectedItem.Text + " GROUP BY Name ";
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Distinct Year from MonthlySales Order By DESC";
using (DataSet objDs = new DataSet())
{
using (SqlDataAdapter dAdapter = new SqlDataAdapter())
{
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddItems.DataSource = objDs.Tables[0];
ddItems.DataTextField = "Year";
ddItems.DataValueField = "Year";
ddItems.DataBind();
ddItems.Items.Insert(0, "Select");
}
}
}
}
}

Resources