Insert if not exist C# SqlCommand - c#

I am trying to add datatable if the data is not existing before
public async Task saveBetEntity(List<BetEntity> betList)
{
DataTable dt = new DataTable();
// dt.Columns.Add("ItemId");
dt.Columns.Add("Player_no");
dt.Columns.Add("PLAYER_BET_NUMBER");
dt.Columns.Add("BET_PLACED_DATE");
dt.Columns.Add("OVER_1000_SEK");
dt.Columns.Add("EVENT_NAME");
dt.Columns.Add("LEAGUE");
dt.Columns.Add("BET_OFFER_TYPE");
dt.Columns.Add("CRITERIA_NAME");
dt.Columns.Add("IS_LIVE");
dt.Columns.Add("BET_LABEL");
dt.Columns.Add("ODDS");
dt.Columns.Add("BET_OUTCOME");
if (betList != null && betList.Count > 0)
{
foreach (var item in betList)
{
DataRow dr = dt.NewRow();
dr["Player_no"] = item.Player_no;
dr["PLAYER_BET_NUMBER"] = item.PLAYER_BET_NUMBER;
dr["BET_PLACED_DATE"] = item.BET_PLACED_DATE;
dr["OVER_1000_SEK"] = item.OVER_1000_SEK;
dr["EVENT_NAME"] = item.EVENT_NAME;
dr["LEAGUE"] = item.LEAGUE;
dr["BET_OFFER_TYPE"] = item.BET_OFFER_TYPE;
dr["CRITERIA_NAME"] = item.CRITERIA_NAME;
dr["IS_LIVE"] = item.IS_LIVE;
dr["BET_LABEL"] = item.BET_LABEL;
dr["ODDS"] = item.ODDS;
dr["BET_OUTCOME"] = item.BET_OUTCOME;
dt.Rows.Add(dr);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
string InsertQuery = string.Empty;
InsertQuery =
"IF NOT EXISTS (SELECT * FROM BetEntities WHERE Player_no =dt.Rows[i][\"Player_no\"].ToString() BEGIN" +
"INSERT INTO BetEntities " +
"(Player_no, PLAYER_BET_NUMBER, BET_PLACED_DATE, OVER_1000_SEK, EVENT_NAME," +
" LEAGUE, BET_OFFER_TYPE, CRITERIA_NAME, IS_LIVE, BET_LABEL, ODDS, BET_OUTCOME) " +
"VALUES ('" + dt.Rows[i]["Player_no"].ToString() + "','" + dt.Rows[i]["PLAYER_BET_NUMBER"].ToString() + "','" + dt.Rows[i]["BET_PLACED_DATE"].ToString()
+ "','" + dt.Rows[i]["OVER_1000_SEK"].ToString() + "','" + dt.Rows[i]["EVENT_NAME"].ToString() + "','" + dt.Rows[i]["LEAGUE"].ToString() +
"','" + dt.Rows[i]["BET_OFFER_TYPE"].ToString() + "','" + dt.Rows[i]["CRITERIA_NAME"].ToString() + "','" + dt.Rows[i]["IS_LIVE"].ToString() +
"','" + dt.Rows[i]["BET_LABEL"].ToString() + "','" + dt.Rows[i]["ODDS"].ToString() + "','" + dt.Rows[i]["BET_OUTCOME"].ToString() + "')" +
" WHERE NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no =dt.Rows[i][\"Player_no\"].ToString()" +
" AND PLAYER_BET_NUMBER = dt.Rows[i][\"PLAYER_BET_NUMBER\"].ToString() " +
" AND BET_PLACED_DATE =dt.Rows[i][\"BET_PLACED_DATE\"].ToString()" +
" AND OVER_1000_SEK =dt.Rows[i][\\\"OVER_1000_SEK\\\"].ToString()\"" +
" AND EVENT_NAME =dt.Rows[i][\\\"EVENT_NAME\\\"].ToString()\"" +
" AND LEAGUE =dt.Rows[i][\\\" LEAGUE\\\"].ToString()\"" +
" AND BET_OFFER_TYPE =dt.Rows[i][\\\"BET_OFFER_TYPE\\\"].ToString()\"" +
" AND CRITERIA_NAME =dt.Rows[i][\\\"CRITERIA_NAME\\\"].ToString()\"" +
" AND IS_LIVE =dt.Rows[i][\\\" IS_LIVE\\\"].ToString()\"" +
" AND BET_LABEL =dt.Rows[i][\\\"BET_LABEL\\\"].ToString()\"" +
" AND BET_OUTCOME=dt.Rows[i][\\\" BET_OUTCOME\\\"].ToString()\"" +
");";
using (SqlConnection destinationConnection = new SqlConnection(_configuration.GetConnectionString("ConnectionAPIConeectionString")))
using (var BetEntities = new SqlCommand(InsertQuery, destinationConnection))
{
destinationConnection.Open();
BetEntities.ExecuteNonQuery();
}
}
}
await Task.CompletedTask;
}
The code works fine if I delete
" WHERE NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no =dt.Rows[i][\"Player_no\"].ToString()" +
" AND PLAYER_BET_NUMBER = dt.Rows[i][\"PLAYER_BET_NUMBER\"].ToString() " +
" AND BET_PLACED_DATE =dt.Rows[i][\"BET_PLACED_DATE\"].ToString()" +
" AND OVER_1000_SEK =dt.Rows[i][\\\"OVER_1000_SEK\\\"].ToString()\"" +
" AND EVENT_NAME =dt.Rows[i][\\\"EVENT_NAME\\\"].ToString()\"" +
" AND LEAGUE =dt.Rows[i][\\\" LEAGUE\\\"].ToString()\"" +
" AND BET_OFFER_TYPE =dt.Rows[i][\\\"BET_OFFER_TYPE\\\"].ToString()\"" +
" AND CRITERIA_NAME =dt.Rows[i][\\\"CRITERIA_NAME\\\"].ToString()\"" +
" AND IS_LIVE =dt.Rows[i][\\\" IS_LIVE\\\"].ToString()\"" +
" AND BET_LABEL =dt.Rows[i][\\\"BET_LABEL\\\"].ToString()\"" +
" AND BET_OUTCOME=dt.Rows[i][\\\" BET_OUTCOME\\\"].ToString()\"" +
I don't want to add the data over and over, that's why I added this code.

You have many errors in your code.
First error is related to not using verbatim string. Without a verbatim string, your SQL Command is a mess and and it is very hard to see the basic errors there that would cause a syntax error on the SQL server side and wouldn't execute at all. You said it works if that "where" didn't exist, but your code is already erroenous without it.
Next there is error from T-SQL point of view if you didn't miss a single quote or double quote and wrote the command string perfectly correct. Your command would conceptually look like:
IF NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no ... )
BEGIN
INSERT INTO BetEntities
( Player_No, ... ) VALUES ( 1, ... )
WHERE NOT EXISTS (Select ... )
END;
However this is invalid T-SQL syntax. You can't use
... VALUES (...) WHERE
To overcome that limitation, you just need to change the syntax a bit and move that "NOT EXISTS" check to the "IF NOT EXISTS" check at top. That is what you are doing after all.
Third error is the one that you might have passed if you put all those + single and double quotes right in your code and that would be a guaranteed disaster in future if not today. You were lucky, indirectly it didn't work and you are here. As I said in comments, never ever write an SQL command like that concatenating strings and putting user inputs within that. That is because:
It makes your SQL code wide open to bad things, widely known as SQL Injection Attack.
Many users get away ignoring the use parameters saying, thinking it is only for SQL Injection Attacks and their code is never open to a real user input from outside or they think they are sanitizing it with some way (well hackers know ways against sanitization if I do know as one mere coder). However, it doesn't only prevent SQL Injection Attack but also take care of the formatting of input values themselves. For datetimes for example, if you were passing it as a string (don't), then it should be in a specific format in order to be independent of server settings. Or with a string, if the string itself contained quote or double quote (ie: O'Hara, 24" pipe) then it would fail or be interpreted in a very different way, although it was an innocent query.
You decide which one of the above reasons are more important in order to use parameters, but at the end I repeat:
Never ever write an SQL command like that concatenating strings and putting user inputs within that.
(I even have a tendency to write that in capitals:)
Then comes another question, why would you ever need a DataTable in between? Directly use the list itself.
A side note by the way, with a list or DataTable or whatever (like
json, xml, ...), if there are many rows to write, then instead of a
loop, you would surely want to do this with the SqlBulkCopy class or
T-SQL Bulk copy or using JSON, XML ...
OK, having said all these, here is a revised version of your code with parameters and verbatim string. You can see the difference in readability at least:
public async Task saveBetEntity(List<BetEntity> betList)
{
if (betList == null)
{
return;
}
string insertQuery = #"IF NOT EXISTS
(
SELECT *
FROM BetEntities
WHERE Player_no = #Player_no
AND PLAYER_BET_NUMBER = #PLAYER_BET_NUMBER
AND BET_PLACED_DATE = #BET_PLACED_DATE
AND OVER_1000_SEK = #OVER_1000_SEK
AND EVENT_NAME = #EVENT_NAME
AND LEAGUE = #LEAGUE
AND BET_OFFER_TYPE = #BET_OFFER_TYPE
AND CRITERIA_NAME = #CRITERIA_NAME
AND IS_LIVE = #IS_LIVE
AND BET_LABEL = #BET_LABEL
AND BET_OUTCOME = #BET_OUTCOME
)
BEGIN
INSERT INTO BetEntities
(
Player_no, PLAYER_BET_NUMBER, BET_PLACED_DATE,
OVER_1000_SEK, EVENT_NAME, LEAGUE,
BET_OFFER_TYPE, CRITERIA_NAME, IS_LIVE,
BET_LABEL, ODDS,BET_OUTCOME
)
VALUES
(#Player_no, #PLAYER_BET_NUMBER, #BET_PLACED_DATE,
#OVER_1000_SEK, #EVENT_NAME, #LEAGUE,
#BET_OFFER_TYPE, #CRITERIA_NAME, #IS_LIVE,
#BET_LABEL, #ODDS, #BET_OUTCOME);
END;
";
using (SqlConnection destinationConnection = new SqlConnection(_configuration.GetConnectionString("ConnectionAPIConeectionString")))
using (var insertCommand = new SqlCommand(insertQuery, destinationConnection))
{
insertCommand.Parameters.Add("#Player_no", SqlDbType.Int);
insertCommand.Parameters.Add("#PLAYER_BET_NUMBER", SqlDbType.Int);
insertCommand.Parameters.Add("#BET_PLACED_DATE", SqlDbType.DateTime);
insertCommand.Parameters.Add("#OVER_1000_SEK", SqlDbType.Text);
insertCommand.Parameters.Add("#EVENT_NAME", SqlDbType.Text);
insertCommand.Parameters.Add("#LEAGUE", SqlDbType.Text);
insertCommand.Parameters.Add("#BET_OFFER_TYPE", SqlDbType.Text);
insertCommand.Parameters.Add("#CRITERIA_NAME", SqlDbType.Text);
insertCommand.Parameters.Add("#IS_LIVE", SqlDbType.Bit);
insertCommand.Parameters.Add("#BET_LABEL", SqlDbType.Text);
insertCommand.Parameters.Add("#ODDS", SqlDbType.Text);
insertCommand.Parameters.Add("#BET_OUTCOME", SqlDbType.Text);
destinationConnection.Open();
foreach (var item in betList)
{
insertCommand.Parameters["#Player_no"].Value = item.Player_no;
insertCommand.Parameters["#PLAYER_BET_NUMBER"].Value = item.PLAYER_BET_NUMBER;
insertCommand.Parameters["#BET_PLACED_DATE"].Value = item.BET_PLACED_DATE;
insertCommand.Parameters["#OVER_1000_SEK"].Value = item.OVER_1000_SEK;
insertCommand.Parameters["#EVENT_NAME"].Value = item.EVENT_NAME;
insertCommand.Parameters["#LEAGUE"].Value = item.LEAGUE;
insertCommand.Parameters["#BET_OFFER_TYPE"].Value = item.BET_OFFER_TYPE;
insertCommand.Parameters["#CRITERIA_NAME"].Value = item.CRITERIA_NAME;
insertCommand.Parameters["#IS_LIVE"].Value = item.IS_LIVE;
insertCommand.Parameters["#BET_LABEL"].Value = item.BET_LABEL;
insertCommand.Parameters["#ODDS"].Value = item.ODDS;
insertCommand.Parameters["#BET_OUTCOME"].Value = item.BET_OUTCOME;
insertCommand.ExecuteNonQuery();
}
}
await Task.CompletedTask;
}
Note: I made guesses on the real SqlDbTypes. Reality might be different, and your list content might not be checked already (ie: It may contain a string value for something that is DateTime or a number, I skipped checking things like that which you should control with TryParse, if that is a possibility. With proper Lists it shouldn't be).

You will need to do it as you were doing before, otherwise, you are sending a string that SQL does not interpret:
Instead of this:
" WHERE NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no =dt.Rows[i][\"Player_no\"].ToString()" +
Do this for each value from the datatable:
" WHERE NOT EXISTS ( SELECT * FROM BetEntities WHERE Player_no = " + dt.Rows[i]["Player_no"].ToString() +

Related

C# insert loop fails for cassandra

I am trying to insert rows into cassandra table using C# datareader loop, after insert one records it give me the below error
Error:{"Object cannot be cast from DBNull to other types."}
What am i doing wrong
--Code
ConnectionString._SQLServerName = txtsql.Text;
ConnectionString._DBName = "casmonitor";
SqlConnection MyConn = ConnectionString.GetOpenedConnection();
SqlCommand MyCommand = ConnectionString.GetOpenedConnection().CreateCommand();
SqlDataReader SqlReader;
string sqltext = ("select * from DBAdmin..[stockhist1] (nolock)");
MyCommand.CommandText = sqltext;
SqlReader = MyCommand.ExecuteReader();
while (SqlReader.Read())
{
ISession CluSession = cluster2.Connect("dbs");
var ps = CluSession.Prepare("insert into stocks (id,name,price1,price2,price3,price4) values (?,?,?,?,?,?)");
// var dbstring= "insert into stocks (id,name,price1,price2,price3,price4) values (" + SqlReader["id"].ToString() + ",'" + SqlReader["name"].ToString() + "'," + Convert.ToUInt64(SqlReader["price1"].ToString()) + "," + Convert.ToUInt64(SqlReader["price2"]) + "," + Convert.ToUInt64(SqlReader["price3"]) + "," + Convert.ToUInt64(SqlReader["price4"]) + ");";
// CluSession.Execute(dbstring);
// CluSession.Execute("insert into stocks (id,name,price1,price2,price3,price4) values (" + SqlReader["id"].ToString() + ",'" + SqlReader["name"].ToString() + "'," + Convert.ToUInt64(SqlReader["price1"].ToString()) + "," + Convert.ToUInt64(SqlReader["price2"]) + "," +Convert.ToUInt64(SqlReader["price3"]) + "," +Convert.ToUInt64(SqlReader["price4"]) + ")");
// var ps = CluSession.Prepare("insert into Product(id,name,p_image) values (?,?,?)");
var statement = ps.Bind(Convert.ToInt32(SqlReader["id"]),SqlReader["name"].ToString() ,Convert.ToDecimal(SqlReader["price1"]) ,Convert.ToDecimal(SqlReader["price2"]) ,Convert.ToDecimal(SqlReader["price3"]),Convert.ToDecimal(SqlReader["price4"]));
CluSession.Execute(statement);
cluster2.Shutdown();
CluSession.Dispose();
}
SqlReader.Close();
MyConn.Close();
One of these values (the Convert.To....()) is returning null from the database
var statement = ps.Bind(Convert.ToInt32(SqlReader["id"]),SqlReader["name"].ToString() ,Convert.ToDecimal(SqlReader["price1"]) ,Convert.ToDecimal(SqlReader["price2"]) ,Convert.ToDecimal(SqlReader["price3"]),Convert.ToDecimal(SqlReader["price4"]));
You cannot, for example, convert a DBNull to a decimal or int.
I would suggest you create a function that you can pass each of these into, and then return either a 0 (where DBNull) or the value
Something like this (not tested, just quick and dirty):
public static decimal GetDecimalValue(SqlDataReader reader, string fieldName)
{
if (!reader.IsDBNull(reader[fieldName])))
return reader.GetDecimal(reader[fieldName]);
else
return 0;
}
then adjust your statement to:
var statement = ps.Bind(Convert.ToInt32(SqlReader["id"]),
SqlReader["name"].ToString() ,
GetDecimalValue(SqlReader, "price1"),
GetDecimalValue(SqlReader, "price2"),
GetDecimalValue(SqlReader, "price3"),
GetDecimalValue(SqlReader, "price4"));`
Create one for int's too (haven't done that for you in the above)

C#: comparing datetimepicker with MS access date

I am using ms access as database that contains field identified as (short date)
i inserted time to that field from datetimepicker in C# using the following query:
string query = #"insert into category_in (category_id,amount_in,dates)
values ('" + ids + "','" + amount2 + "','"+dateTimePicker1.Text+"')";
and everything is ok. But when i am trying to compare the date in the database with date from another datetimpicker it doesnot work. This is the query of comparsion:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= " + dateTimePicker1.Value.Date.ToShortTimeString() + " "
"and category_in.dates<= " + dateTimePicker2.Value.Date.ToShortTimeString() + "";
when i use dateTimePicker.value.Date it gives me the following error
Syntax error (missing operator) in query expression
'category_in.dates>= 16/08/2015 12:00:00 ص and category_in.dates<=
20/08/2015 12:00:00 ص
but when i add dateTimePicker.value.Date.ToShortTimeString no results returned although there are some data between these dates
do i have to change the insertion method?
I'm surprised that all three answers (so far) have suggested that you continue using dynamic SQL and fiddle with your string-formatted dates and delimiters until you get something that works.
That's just dumb.
The DateTimePicker control returns a System.DateTime value so you should just use that as part of a parameterized query, something like this:
using (var conn = new OdbcConnection(
#"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
#"Dbq=C:\Users\Public\Database1.accdb"))
using (var cmd = new OdbcCommand("INSERT INTO MyTable (DateTimeField) VALUES (?)", conn))
{
conn.Open();
cmd.Parameters.Add("?", OdbcType.DateTime).Value = dateTimePicker1.Value.Date;
cmd.ExecuteNonQuery();
}
I think your code should use the # delimiter for date expressions in Access:
string query = #"insert into category_in (category_id,amount_in,dates)
values ('" + ids + "','" + amount2 + "',#" + DateTime.Parse(dateTimePicker1.Text).ToString("yyyy'/'MM'/'dd") + "#)";
and:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates >= #" + dateTimePicker1.Value.Date.ToString("yyyy'/'MM'/'dd") + "# "
"and category_in.dates <= #" + dateTimePicker2.Value.Date.ToString("yyyy'/'MM'/'dd") + "#";
Try changing your query to this:
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= #" + dateTimePicker1.Value.ToShortDateString() + "# "
"and category_in.dates<= #" + dateTimePicker2.Value.ToShortDateString() + "#";
The issue is your dates are strings. Add Single quotes before and after your datetime values. Like this...
query = "SELECT products.category, category_in.dates FROM products, category_in where " +
"category_in.dates>= '" + dateTimePicker1.Value.Date.ToShortTimeString() + "' "
"and category_in.dates<= '" + dateTimePicker2.Value.Date.ToShortTimeString() + "'";
This will allow the query engine to implicitly convert the strings to datetimes.

Executing Query contain string without using quotes

So i am trying to delete data in database based on two things.
First is a combox box which selects the column name and second is the value whose row is to be deleted.
(#"SELECT * FROM Contacts WHERE " + var + " LIKE " + textBox1.Text + ";");
Now the problem here is that as long as the value in the textBox is numerical this query will work fine. However if it is a string value the query will fail because i haven't inserted the single quote.
Is there anyway i can make just a single unified query for handling both numerical and text data.
Okay, let's not do this. We need to just use parameters.
(#"SELECT * FROM Contacts WHERE " + var + " LIKE #" + var + ";");
...
cmd.Parameters.AddWithValue("#" + var, textBox1.Text);
So the overall code might look something like this:
string varName = string.Format("#{0}", var);
string sql = string.Format("SELECT * FROM Contacts WHERE {0} LIKE #{0}", var);
using (SqlConnection c = new SqlConnection(cString))
using (SqlCommand cmd = new SqlCommand(sql, c))
{
cmd.Parameters.AddWithValue(varName, textBox1.Text);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
}
Also, have a look at this post on my blog. It talks about what I just went through, as well as how to safely do a LIKE.
Try using parameterized query
SqlCommand command = new SqlCommand(
#"SELECT * FROM Contacts WHERE " + var + " LIKE #param", connection));
command.Parameters.AddWithValue("#param", textBox1.Tex);
You need to add quotes arounf the value so that it will accept string as well numerical values
(#"SELECT * FROM Contacts WHERE " + var + " LIKE '" + textBox1.Text + "';");
How about this:
(#"SELECT * FROM Contacts WHERE " + var + " LIKE " _
+ iif(isnumeric(textBox1.Text),textbox1.text, "'" +textbox1.text +"'" + ";");
That's a vb-centric IIF statement, but there's an equivolent in C#.
(#"SELECT * FROM Contacts WHERE " + var + " LIKE '" + textBox1.Text + "';");
U can check the value whether its integer or string and format different query accordingly.U can use like operator also.
String str = Console.ReadLine();
int myval;
String query="";
if(int.TryParse(str,out myval))
query=#"SELECT * FROM Contacts WHERE " + var + " LIKE " + myval + ";";
else
query=#"SELECT * FROM Contacts WHERE " + var + " LIKE '" + str + "';";

Insert command error in OleDB

A little noob says HY.
I have a small problem with a homework project in Microsoft Visual Studio 2010.
Also, i work in C#.
I must do a site for selling products and i have an Access database.
So, the problem is this: i wrote code but it seems something is wrong and i don't know what!
When i try to Add a command by site i receive an error:
Data type mismatch in criteria expression.
Code is:
string date = DateTime.Now.ToShortDateString();
string string_baza_de_date = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\BogCs\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\magazin.mdb";
OleDbConnection ConexiuneSQL = new OleDbConnection(string_baza_de_date);
ConexiuneSQL.Open();
int numar_total_de_produse = CheckBoxList1.Items.Count; // se numara produsele
for (int i = 0; i < numar_total_de_produse; i++) // de la primul articol din CheckBoxList1 pana la ultimul
{
if (CheckBoxList1.Items[i].Selected == true) // daca am selectat un produs
{
// interogarea comenzii:
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, ID_produs, produs, tip_produs, data_comanda, pret) VALUES ("
+ TextBox1.Text + ",'" + TextBox2.Text + "',"
+ CheckBoxList1.Items[i].Value + ",'" + CheckBoxList1.Items[i].Text + "', 'Televizoare LED','"
+ data_curenta + "','" + GridView3.Rows[i].Cells[3].Text.ToString() + "');";
OleDbCommand comanda_inserare_comanda = new OleDbCommand(interogare_adauga_comanda, ConexiuneSQL);
comanda_inserare_comanda.ExecuteNonQuery();
}
}
ConexiuneSQL.Close();
GridView3.Visible = false;
Button1.Visible = false;
Button2.Visible = false;
CheckBoxList1.Visible = false;
Label1.Visible = false;
TextBox1.Visible = false;
Label2.Visible = true;
When i press "Add command" gives me that error and i don't know how to solve!
you have to put " ' " before and after textbox1.text
so it would look like this:
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, ID_produs, produs, tip_produs, data_comanda, pret) VALUES ('" + TextBox1.Text + "','" + TextBox2.Text + "', " + CheckBoxList1.Items[i].Value + ",'" + CheckBoxList1.Items[i].Text + "', 'Televizoare LED','"+ data_curenta + "','" + GridView3.Rows[i].Cells[3].Text.ToString()+ "');";
Probably the error lies in some of your strings used to build the command.
As usual this is the first obvious reason to use parametrized query.
Let the framework code format your strings according to the rules of the current database.
The most important reason however, is the Sql Injecton problem
So let me change your code in this way to get rid of that ugly string concatenation
string interogare_adauga_comanda = "INSERT INTO comanda_finala (ID_comanda, ID_client, "+
"ID_produs, produs, tip_produs, data_comanda, pret) " +
"VALUES (?,?,?,?,?,?,?)";
OleDbCommand comanda_inserare_comanda = new OleDbCommand(interogare_adauga_comanda, ConexiuneSQL);
comanda_inserare_comanda.Parameters,AddWithValue("#p1",TextBox1.Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p2",TextBox2.Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p3",CheckBoxList1.Items[i].Value );
comanda_inserare_comanda.Parameters,AddWithValue("#p4",CheckBoxList1.Items[i].Text );
comanda_inserare_comanda.Parameters,AddWithValue("#p5","Televizoare LED");
comanda_inserare_comanda.Parameters,AddWithValue("#p6",data_curenta);
comanda_inserare_comanda.Parameters,AddWithValue("#p7",GridView3.Rows[i].Cells[3].Text.ToString());
comanda_inserare_comanda.ExecuteNonQuery();
Also, keep in mind that you should pass the value to the parameters with the correct datatype expected by the database field. For example, if your first field ID_comanda is numeric then the line of the relative parameter should be changed to
comanda_inserare_comanda.Parameters,AddWithValue("#p1",Convert.ToInt32(TextBox1.Text));
and this raises another problem. Did you check if the text in the TextBox1 is really a number?

Dynamically build SQL " OR " query in c#

I am having problem with my asp.net app, in which I am dynamically building SQL query where I am using WHERE clause and adding OR depending on the fields which is entered. here is the scenario.
I have a Four TextBox, out of 2 is DateTime
i would like to search in the database if there is a value in any one text-box and return the results that is bind to a GridView. Now, if there is more than one text-box value then i need to add that as well and build OR in where clause. if there are no values in any one of the text-box then need to return all the results. BUT i am having problem in building the query as i have to go through the if else loop to see if there is any value or null. here is my code.
StringBuilder selectQuery = new StringBuilder();
disCode = SearchTextCouponCode.Text;
disName = SearchTextCouponName.Text;
if(StartDate.SelectedDate != null)
startDate = StartDate.SelectedDate.ToString("yyyy-MM-dd");
if(EndDate.SelectedDate != null)
endDate = EndDate.SelectedDate.ToString("yyyy-MM-dd");
// here is the main thing where i am getting the error
if (!string.IsNullOrEmpty(disCode))
{
selectQuery.Append("DISCOUNTCode = '" + disCode + "'");
}
if (!string.IsNullOrEmpty(disName))
{
selectQuery.Append(" OR DISCOUNTName = '" + disName + "'");
}
if (startDate != "0001-01-01")
{
selectQuery.Append(" OR StartDate = '" + startDate + "'");
}
if(endDate != "0001-01-01")
selectQuery.Append(" OR EndDate = '" + endDate + "'");
// I am using Object Data Source and the method i am passing is taking care of the SQL injection
DataSourceDis.SelectParameters["sqlCriteria"].DefaultValue = selectQuery.ToString();
GridDis.DataBind();
now, when i run the app, and leave the disCode text-box empty, then the query start with OR and gives me the error that incorrect syntax near where ..
please help.
/////////////////////////////////////////////////////////
i am calling another method after building up this query which is taking care of SQL Injection
/////////////////////////////////////////////////////////
The easiest thing you could do is change WHERE to:
WHERE 1=0
And then ensure all of your WHERE conditions start with OR
As Richard has pointed out however, this is not best practice, and you would be better using a stored procedure or LINQ. Using stored procedures you could pass all these parameters to the procedure and then do something like:
AND (#disName IS NULL OR DiscountName=#disName)
You could set all lines to have " OR " at the end (instead of the start), such as...
selectQuery.Append("DISCOUNTCode = '" + disCode + "' OR ");
And then before using the .ToString() have...
if(selectQuery.Length > 0)
{
selectQuery.Length -= 4;
}
If you use the WHERE 1=0 OR solution, you may get performance impacts.
I'd recommend creating a variable to mark the conjunction and changing it when you add a condition
string conjuction = " ";
if (!string.IsNullOrEmpty(disCode))
{
selectQuery.Append(conjunction);
selectQuery.Append("DISCOUNTCode = '" + disCode + "'");
conjuction = " OR ";
}
if (!string.IsNullOrEmpty(disName))
{
selectQuery.Append(conjunction);
selectQuery.Append("DISCOUNTName = '" + disName + "'");
conjuction = " OR ";
}
etc.
I don't know where your inputs are coming from, but be aware of the potential for a SQL injection attack in your current code.
I'd generally do it like this;
var conds = new List<string> ();
// here is the main thing where i am getting the error
if (!string.IsNullOrEmpty(disCode))
{
conds.Add("DISCOUNTCode = '" + disCode + "'");
}
if (!string.IsNullOrEmpty(disName))
{
conds.Add("DISCOUNTName = '" + disName + "'");
}
if (startDate != "0001-01-01")
{
conds.Add("StartDate = '" + startDate + "'");
}
if(endDate != "0001-01-01")
conds.Add("EndDate = '" + endDate + "'");
selectQuery.Append(String.Join(" OR ",conds));
It's a bit hideous building queries like this - better to use prepared statements or LINQ or your own query building class.
A valid Sql query e.g. SELECT * FROM EMPLOYEE WHERE Name = 'Hat' OR SURNAME = 'SOFT'
Looks like you case when the query starts with OR your StringBuilder Appends the query like this
SELECT * FROM EMPLOYEE WHERE OR SURNAME = 'SOFT' and its invalid becuase the OR KEYWORD directly after WHERE
when your disCode text-box is empty then Condition will be "OR DISCOUNTName" which is wrong you can not use "OR" after where
if (!string.IsNullOrEmpty(disCode))
{
selectQuery.Append("DISCOUNTCode = '" + disCode + "'");
}
if (!string.IsNullOrEmpty(disName))
{
selectQuery.Append(" OR DISCOUNTName = '" + disName + "'");
}

Categories