I am executing a MS Access Query through c#. Below is the query
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours" +
"' WHERE EMPID = '" + Eno +
"'AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") +
"# FROM INOUTPunching";
which is giving below error
{"The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect."}
I need to know:
Why is this not working?
Is there any simplier method?
You should place the FROM clause before the WHERE clause. That is the problem with your query. And you have an extra single quote which should be removed. This is the query you should write:
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours FROM INOUTPunching " +
" WHERE EMPID = '" + Eno +
"'AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + "#";
And about a simpler method: no, this is the simplest method but it is prone to SQL injection attacks. Replace it with a parameterized query (assuming you have an OldDbCommand name cmd):
String SelWHQuery = "SELECT DateDiff('n',INTime,OUTTime)\\60 & '.' & Format(DateDiff('n',[INTime],[OUTTime]) Mod 60,'00') AS Workedhours FROM INOUTPunching " +
" WHERE EMPID = #EmpId AND RDate=# "+ DateTime.Now.Date.ToString("yy-MM-dd") + "#";
cmd.CommandType = CommandType.Text;
cmd.CommandText = SelWHQuery;
cmd.Parameters.AddWithValue("#EmpId", Eno);
Related
When I execute a query for the population of a table I get an error on only two occurrence. In particular, when the name field has some value like this:
K'Ogladbach
Now the apostrophe causes an issue, because the query interprets this command like a new value and this is wrong.
This is my structure for the query in SQL:
string sql = #"insert into Team (name, code, shortName, squadMarketValue,
crestUrl, link_self, link_fixtures, link_players, caption)
values ('" + item.name + "', '" + item.code + "', '" +
item.shortName + "', '" + item.squadMarketValue + "', '" +
item.crestUrl + "', '" + item._links.self.href + "', '" +
item._links.fixtures.href + "', '" + item._links.players.href + "', '" +
campionato + "')";
how you can see each new value is rapresented by ' value ',
so if in the value there's a " ' " it's a problem because the query failed the table population. Hopefully, there is a solution.
Use SqlParamerterized queries rather than raw SQL. This will help prevent SQL Injection and also provide a robust solution.
SqlCommand command = new SqlCommand("INSERT INTO Team (name) VALUES (#name)", con);
command.Parameters.Add("#name", SqlDbType.NVarChar).Value = item.name;
// Add the rest of the parameters here
command.ExecuteNonQuery(); // Execute the command
SqlParamerterized queries is the best approach
You can also replace a ' with a '' in the data
That is not a double quote - it is two single quotes
E.G. K'Ogladbach to K''Ogladbach
I am looking to perform a search on multiple columns from an access database in C#.
The data is built in rows with each column either holding relevant data or "*" as a wildcard.
So as a rough example:
If i had data that was (, indicates new cell)
Ford, Fiesta, *, 1998
then if i had a value...
Ford, Fiesta, Petrol, 1998
it would find and display the row of data.
Currently I am trying:
string sql = "SELECT * FROM [mydatabase]
WHERE Manufacturer ='" + textBox1.Text +
"' OR Manufacturer='*' AND Model ='" + textBox2.Text +
"' OR Model='*' AND Fuel ='" + textBox3.Text +
"' OR Fuel='*' AND Year='" + textBox4.Text + "' OR Year='*'";
But this is bringing up all values rather than filtering them down. Is there a way of using and if/else within the query instead of OR?
If you want to use a wild card, I would just exclude it from the where clauses.
Alternateively, if you want to search all columns as one string you could add them all to a new column in the select list.
for example:
public void GetCars(string manufacturer, string model, string fuel, DateTime? year, string searchString)
{
string query = #"
SELECT *,
ISNULL([Manufacturer],'') + ' ' + ISNULL([Model],'') + ' ' ISNULL([Fuel],'') + ' ' ISNULL('Year', '') AS [SearchString]
FROM [MyDatabase]
WHERE [Manufacturer]=#Manufacturer ";
if (!String.IsNullOrEmpty(model))
query += #"AND [Model]=#Model ";
if (!String.IsNullOrEmpty(fuel))
query += "AND [Fuel]=#Fuel ";
if (year.HasValue)
query += "AND [Year]=#Year ";
if (!String.IsNullOrEmpty(searchString))
query += #"AND [SearchString] Like '%#SearchString%' ";
using (SqlCommand sqlCommand = new SqlCommand(query))
{
sqlCommand.Parameters.AddWithValue("#Manufacturer", manufacturer);
if (!String.IsNullOrEmpty(model))
sqlCommand.Parameters.AddWithValue("#Model", model);
if (!String.IsNullOrEmpty(fuel))
sqlCommand.Parameters.AddWithValue("#Fuel", fuel);
if (year.HasValue)
sqlCommand.Parameters.AddWithValue("#Year", year.Value);
if (!String.IsNullOrEmpty(searchString))
sqlCommand.Parameters.AddWithValue("#SearchString", searchString);
//Execute to data table etc
}
}
Instead of Manufacturer ='" + textBox1.Text + "' OR Manufacturer='*', you can use coalesce, which is sort of an if/else:
string sql = "... Manufacturer = coalesce('" + textBox1.Text + "', '*') ...";
In that way, you only need ands, and not mixed with or. This is probably giving the problem now, since the ors cause the and not to be evaluated.
You can also add parenthesis around the and, so the or will be applied only inside the parenthesis:
string sql = "... where (Manufacturer ='" + textBox1.Text + "' OR Manufacturer='*') and ...";
Note you should use parameterized queries, so you would get something like this:
command.CommandText = "select * from ... where Manufacturer = coalesce(#mgr, '*') and ...";
command.Parameters.Add(new SqlParameter("mgr", textBox1.Text));
I'm using SQL Server 2008, with a C# front end. I'm trying to pass a SQL string from C# to SQL Server, and there are 2 fields in my WHERE statement that sometimes might contain NULL values. I've got this code on my Page Load in the code-behind (this is for a report that will be placed in a datagrid):
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
string Val_Value = Convert.ToString(Request.QueryString["Val_Val"]);
string Trk_Value = Convert.ToString(Request.QueryString["Trk_Val"]);
string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
string sqlquery;
sqlquery = "Select DISTINCT PL.PROC_NM as Agent_Name, CCM.UNIQUE_CLAIM_ID as Unique_ID, CCM.CLAIM_ID as Claim_Number, ";
sqlquery = sqlquery + "CCM.SOCSEC as Employee_Last_Digit, CCM.DATE_IMPORTED as Import_Date, CCM.Orig_Open_Date as Original_Review_Date, ";
sqlquery = sqlquery + "AGL.ACCT_GRP as Account_Name, AL.ACCT_NUM as Account_Number, CCM.CDBBEN as Benefit_Option, CCM.BENEFIT_TYPE1 as Benefit_Type1, ";
sqlquery = sqlquery + "CCM.BENEFIT_TYPE2 as Benefit_Type2, CCM.BENEFIT_TYPE3 as Benefit_Type3, CCM.Cmplt as Review_Validated, CCM.Vldtn_Cmmnts as Validation_Comments, ";
sqlquery = sqlquery + "CCM.Gtkpr_Cmmnts as Gatekeeper_Comments, TS.StatusText as Tracking_Status ";
sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "LEFT JOIN ACCT_LIST AL ON AL.ACCT_NUM = CCM.CDBACC ";
sqlquery = sqlquery + "LEFT JOIN ACCT_GRP_LIST AGL ON AGL.ACCT_GRP_PK = AL.ACCT_GRP_FK ";
sqlquery = sqlquery + "LEFT JOIN TrackingStatus TS ON TS.StatusCode = CCM.TrackingStatus ";
sqlquery = sqlquery + "WHERE CCM.Spare LIKE '" + DDL_Value + "' AND CCM.Cmplt LIKE '" + Val_Value + "' AND CCM.TrackingStatus IN (" + Trk_Value + ") AND CCM.DATE_IMPORTED >= '" + StDt_Value + "' AND CCM.DATE_IMPORTED <= '" + EnDt_Value + "'";
}
The code is sound, it works perfectly fine if a value is selected for all report parameters. The problem is CCM.Spare and CCM.Cmplt can have specific values chosen from a dropdown, or they can be left blank. If left blank, then they need to pull ALL values, whether they're NULL or not. When I leave one (or both) blank, that's where the SQL fails.
I tried checking for blanks and setting the variable equal to '%', but that obviously isn't working; it will only pick up records where there is a value in the field.
I want to do this with one statement if possible before I go cludging it with some If/Then/Else loops.
Is this possible?
try this, I just included the code for the first criteria.
As recommended above, don't concatenate your parameters; the second option is the best way to do it:
sqlquery = sqlquery +
"WHERE CCM.Spare " + (DDL_Value == null ? "IS NULL" : "LIKE '" + DDL_Value + "'") + " AND ...";
sqlquery = sqlquery +
"WHERE CCM.Spare " + (DDL_Value == null ? "IS NULL" : "LIKE #par1") + " AND ...";
Additionaly to increase the speed of your query you could do:
sqlquery = sqlquery +
"WHERE " + (DDL_Value != null ? "CCM.Spare LIKE #par1 AND " : "") + "...";
this will ignore the whole criteria on CCM.Spare if your parameter is null.
If you want all possible values of CCM.Spare and CCM.Cmplt, you simply need to leave off the predicate. Build a separate query (preferable using parametrized queries, as marc_s points out) that omits the WHERE clause referencing the empty dropdown value.
I am receiving
OleDBException was unhandled error of "Syntax error (missing operator) in query
expression '(StudentID = 100' OR StudentName = 'Nick' OR StudentCNCI = '78894452)Bob'."
private void btnFind_Click(object sender, EventArgs e)
{
string title = textBox1.Text.ToString();
string queryString = "SELECT * FROM Students WHERE (StudentID = " + StudIDTb.Text.ToString() + "' OR StudentName = '" + StudNameTb.Text.ToString() + "' OR StudentCNCI = '" + StudCNCITb.Text.ToString() + ")" + title;
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Connection = myCon;
myCon.Open();
OleDbDataReader dr = command.ExecuteReader(); // error pointing here
while (dr.Read())
{
StudIDTb.Text += String.Format("StudentID: {0}\n", dr["StudentID"].ToString());
StudNameTb.Text += String.Format("StudentName: {0}\n", dr["StudentName"].ToString());
StudCNCITb.Text += String.Format("StudentCNIC: {0}\n", dr["StudentCNIC"].ToString());
StudDOBTb.Text += String.Format("StudentDOB: {0}\n", dr["StudentDOB"].ToString());
}
myCon.Close();
}
I have also tried...
string queryString = "SELECT * FROM Students WHERE (StudentID = " + StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text + "' OR StudentCNCI = '" + StudCNCITb.Text + ")" + title;
I don't want to give you wrong impression I am "lazy" but I am assuming I am getting this error because I have query it incorrectly or I have made a typo error or could it be something else. Please can someone help me, thanks in advance.
ps I know I am getting criticism for not using parameterized queries. I will change it once I got the basic right. I know a lot of similar questions have been asked here but I still can't get it right.
UPDATE 1
I have changed it to
"SELECT * FROM Students WHERE StudentID = " + StudIDTb.Text + " OR StudentName = '" + StudNameTb.Text + "', OR StudentCNCI = '" + StudCNCITb.Text + ")";
I am now receiving error of...
Syntax error (comma) in query expression
I am looking into it
Update 2
string queryString = "SELECT * FROM Students WHERE StudentID = " + StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text + "' OR StudentCNCI = '" + StudCNCITb.Text + "'";
Receiving the same error.
Looking into it
Update 3
If it can't be solved I do it the way it should be, using parameterized queries as highly recommended if it means to solve the problem and probably easy to spot any problems with the code
It's telling you that your query is invalid. You have this
SELECT *
FROM Students
WHERE (StudentID='a' OR StudentName='b' or StudentCNCI='c')Bob
It's not liking that Bob on the end and it's not clear why you need it. Explain what your intent is there, or just get rid of it as it doesn't appear to be necessary for your query.
string queryString = "SELECT * FROM Students WHERE StudentID = '" +
StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text +
"' OR StudentCNCI = '" + StudCNCITb.Text + "'";
As you mention in your post, you need to parameterize your query also. Let us know if you need help with that, but it is pretty straightforward, and a common post on here, so you already have plenty of resources to figure that out.
EDIT: If you like, you can remove the parenthesis. You'd really only need then if you were going to do a subquery or some such thing. They won't hurt your query, they're just not really necessary.
SELECT *
FROM Students
WHERE StudentID='a' OR StudentName='b' or StudentCNCI='c'
Also, from other comments, you actually have multiple quote mismatches (one at the beginning and another at the end).
Okay, so in the past few weeks I've probably written about 40 select statements. So, I know how to do it. And I've just written another one, but this time I need to use ComboBox values to match against, and it keeps resulting in the names of the column (the right column, mind you), instead of what's inside the column.
string st = "SELECT '" + txtchange.Text + "'
FROM mysql_9269_dbase." + pages.Text + "";
MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
cd.CommandType = CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();
while(msdr.Read())
{
txt.Text = msdr[0].ToString();
}
Now, why is it returning the column name instead of the content of that column?
Lose the single quotes.
Change
"SELECT '" + txtchange.Text + "' "
to
"SELECT " + txtchange.Text + " "
In sql you can do it like this.
string query = "Execute("+"'SELECT " + txtchange.Text + " FROM mysql_9269_dbase." + pages.Text + "')";