Confused about database select query - asp.net

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

Related

Troubles when fetching data from table with a query with a parameter

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

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.

How to File Upload csv to SQL database on intranet VB.NET site

I am having problems uploading CSV files to my SQL Database. I am trying to achieve this through the File Upload technique on an intranet site. The intranet site is for me and another user to have the ability to file upload these CSVs (in case one of us is out).
I've used the following;
Dim errorList As String = String.Empty
Dim returnValue As Integer = 0
Dim SQLCon As New SqlClient.SqlConnection
Dim SQLCmd As New SqlClient.SqlCommand
Dim ErrString As String
Dim countRecs As Integer = 0
Dim batchid As Integer = GetNextBatchNumber("PartsImport")
Using tf As New TextFieldParser(fileandpath)
tf.TextFieldType = FileIO.FieldType.Delimited
tf.SetDelimiters(",")
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (ID,PartName,PartID,Price,ShipAddress) " _
+ " values ('" + row(0) + "','" + row(1) + "','" _
+ row(2) + "','" + row(3) + "','" + row(4) + "')"
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close()
SQLCon.Dispose()
SQLCmd.Dispose()
When I click the form button to upload, it gives me a success message but when I look in the actual table, it is still blank.
Any ideas? Appreciate it
Thanks
Dave
private void UploaddataFromCsv()
{
SqlConnection con = new SqlConnection(#"Data Source=local\SQLEXPRESS;Initial Catalog=databaseName;Persist Security Info=True;User ID=sa");
string filepath = "C:\\params.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while ( !sr.EndOfStream )
{
value = sr.ReadLine().Split(',');
if(value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "[Base].[PartsImport]";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
Try catching a SqlException and seeing if there is a formatting issue with your request. If you have an identity column on the ID, you shouldn't set it explicitly from your CSV as that may cause a potential duplicate to be submitted to your database. Also, I suspect that you have some type mismatches in your types since you are putting quotes around what appear to be number columns. I would recommend you consider replacing the string concatenation in your query to using parameters to avoid issues with improper quote escaping (ie. what would happen if you have a PartName of "O'Reily's auto parts"?) Something like this may work. Note, I've been in the LINQ world for so long, I may have some syntax errors here.
SQLCon.ConnectionString = ConfigurationManager.ConnectionStrings("DB00ConnectionString").ConnectionString
SQLCon.Open()
SQLCmd.CommandType = CommandType.Text 'Setup Command Type
SQLCmd.CommandText = "insert into [Base].[PartsImport] " _
+ " (PartName,PartID,Price,ShipAddress) " _
+ " values (#PartName, #PartID, #Price, #ShipAddress)'"
Dim partNameParam = New SqlParameter("#PartName", SqlDbType.VarChar)
Dim partIdParam = New SqlParameter("#PartID", SqlDbType.Int)
Dim partPriceParam = New SqlParameter("#Price", SqlDbType.Money)
Dim partAddressParam = New SqlParameter("#ShipAddress", SqlDbType.VarChar)
SQLCmd.Parameters.AddRange( {partNameParam, partIdPAram, partPriceParam, partAddressParam})
SQLCmd.Connection = SQLCon
Dim recAdded As String = Now.ToString()
Dim row As String()
While Not tf.EndOfData
Try
row = tf.ReadFields()
Dim x As Integer = 0
If countRecs <> 0 Then
Try
partNameParam.Value = row[1]
partIdParam.Value = row[2]
partPriceParam.Value = row[3]
partAddressParam.Value = row[4]
SQLCmd.ExecuteNonQuery()
Catch ex As Exception
ErrString = "Error while Creating Batch Record..." & ex.Message
End Try
End If
Catch ex As MalformedLineException
errorList = errorList + "Line " + countRecs + ex.Message & "is not valid and has been skipped." + vbCrLf
End Try
countRecs = countRecs + 1
End While
SQLCon.Close() 'TODO: Change this to a Using clause
SQLCon.Dispose()
SQLCmd.Dispose() 'TODO: Change this to a Using clause
With all that being said, if you have any significant number of items to insert, the bulk copy example is a better answer.

The multi-part identifier could not be bound

this error appear when run this code
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT email from reg where email ="+email_tb.Text,con);
con.Open();
comsel.ExecuteNonQuery();
con.Close();
if (comsel == null)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand com = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", con);
con.Open();
com.Parameters.AddWithValue("#fn", firstname_tb.Text);
com.Parameters.AddWithValue("#ln", lastname_tb.Text);
com.Parameters.AddWithValue("#email", email_tb.Text);
com.Parameters.AddWithValue("#reemail", reemail_tb.Text);
com.Parameters.AddWithValue("#pass", pass_tb.Text);
com.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
com.Parameters.AddWithValue("#birth", birthday);
com.ExecuteNonQuery();
con.Close();}
Try putting quotes around email_tb.Text, like this:
"SELECT email from reg where email ='" + email_tb.Text + "'"
Try:
SqlCommand comsel = new SqlCommand("SELECT email from reg where email ='" + email_tb.Text + "'", con)
E.g. your string literal need to be in quotes. Better yet, use a SqlParameter!

Adding the WHERE Statement in the SQL

Hi guys after the help in another post I managed to get the following Update SQL statement to work however I wish to add a WHERE.
So I have:
cmd = new SqlCommand("UPDATE Schedule SET Schd_Avaliable = '" + "No" + "'", con);
cmd.ExecuteNonQuery();
And I want to add a Where which looks for the Schd_ID in the table and a schdid which is from a session however with all the punctuation im unsure where to put it.
This is the Where I made:
WHERE Schd_ID = schdid
just unsure where to put that exactly in the line below without it throwing an error:
cmd = new SqlCommand("UPDATE Schedule SET Schd_Avaliable = '" + "No" + "'", con);
cmd.ExecuteNonQuery();
Mark
Try this:
string sql = "UPDATE Schedule SET Schd_Avaliable = 'No' WHERE Schd_ID = #schdid";
cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#schdid", int.Parse(Session["SchdID"].ToString()));
cmd.ExecuteNonQuery();
Modify as needed for your session, and column names.
It is recommended to use Sql Parameters in this situation.
cmd = new SqlCommand(#"UPDATE Schedule
SET Schd_Avaliable = #ScheduleAvailable
WHERE Schd_ID = #ScheduleID", con);
cmd.Parameters.Add(new SqlParameter("#ScheduleAvailable", "No") );
cmd.Parameters.Add(new SqlParameter("#ScheduleID", schdid.ToString()));
cmd.ExecuteNonQuery();
cmd = new SqlCommand("UPDATE Schedule SET Schd_Avaliable = '" + "No" + "' WHERE Schd_ID ='" + schdid + "'", con);
cmd.ExecuteNonQuery();
"UPDATE Schedule SET Schd_Avaliable = '" + "No" + "'" + "WHERE Schd_ID = '" + schdid + '"

Resources