Executing Query contain string without using quotes - c#

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 + "';";

Related

Insert if not exist C# SqlCommand

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() +

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.

Update query issue C#

string sql = "Update stdrecord set firstname='" + fname + "',lastname='" + lname + "',mobile='" + mob + "',phone='" + phn + "',city='" + city + "',province'" + prov + "'where id='" + id + "'";
error :
System.Data.SqlClient.SqlException: Incorrect syntax
can anybody cor rectify the query ?
Your missing an equal:
"',province = '" + prov + "' where id='" + id + "'";
And do not build SQL-Queries like this. Please use ADO.Net Parameter.
Equal sign is missing:
,province='" + prov + "' where id='" + id + "'";
string sql = "Update stdrecord set firstname='" + fname + "',lastname='" + lname + "',mobile='" + mob + "',phone='" + phn + "',city='" + city + "',province='" + prov + "'where id='" + id + "'";
You miss = after province and there is no space between prov and where !
Also in this case you are open to SqlInjection, please use SqlCommand.Parameters.
The Query should look like this.
string sql = #"Update stdrecord set firstname=#FName ,lastname=#LastName, mobile=#Mobile,
phone=#Phone,city=#City, province=#Province where id=#ID";
This will protect you from SqlInjection and also sql server will cache your query.
To using command Parameters you need to add this code to your SqlCommand
SqlCommand cmd = new SqlCommand(sql, connectionString);
cmd.Parameters.AddWithValue("#FName", fName);
cmd.Parameters.AddWithValue("#LastName", lname );
cmd.Parameters.AddWithValue("#Mobile", mob);
cmd.Parameters.AddWithValue("#Phone", phn);
cmd.Parameters.AddWithValue("#City", city);
cmd.Parameters.AddWithValue("#Province", prov);
cmd.Parameters.AddWithValue("#ID", id);
With this structure you will not have problems like this in future because you will not add + and ' non stop. Also use # when you build string this give you the possibility to write string on more than one line without using +.
Put a space before Where Clause and equal sign in province column, will get work perfectly

Error - No value given for one or more required parameters

I have a problem working on my project.
I'm trying to read a data from an Excel file. It works fine when I'm trying to select rows which are greater than Col1Value but after I add AND Gender = " + gender; it gives me error "NO VALUE GIVEN FOR ONE OR MORE REQUIRED PARAMETERS" I cannot set a specific gender column because It is different on every excel file although column name is same and error appears when I'm trying to fill the DataSet.
if (boxGender.Text != "")
string gender = boxGender.Text;
string col1Name = lbl1stColumn.Text;
string Query = "select * from [data$] where " +
col1Name + " > " + Col1Value +
" AND Gender = " + gender;
OleDbDataAdapter dacol1 = new OleDbDataAdapter(Query, con);
Column1Data.Clear();
dacol1.Fill(Column1Data)
lblStuCount1Col.Text = Column1Data.Tables[0].Rows.Count.ToString();
You need to enclose the string value in single quotes and the column names in square brackets:
string Query = "select * from [data$] where [" +
col1Name + "] > " + Col1Value +
" AND Gender = '" + gender + "'";
I think you might be missing quotes in your SQL query:
string Query = "select * from [data$] where " + col1Name + " > '" + Col1Value + "' AND Gender = '" + gender +"'";
Note single quote (') symbols added.

Categories