Is there a way to SELECT a database table using a variable? - c#

I tried this statement:
string query = "SELECT question FROM '" + GlobalVariables.dbQCode + "' WHERE [question_code] = '" + GlobalVariables.questionCode + "' ";
and when I run the code it is giving me an exception:
Syntax error in query. Incomplete query clause.
Is there a way where I can use my variable? I want it to work because I want this code to work also:
if (comboBox1.Text == "General Education"){
GlobalVariables.subjectCode = "GenEd_English";
GlobalVariables.dbQCode = "Gen_Ed_Question_Items";
GlobalVariables.dbCCode = "Gen_Ed_Choice_Bank";
if (comboBox2.Text == "English")
{
GlobalVariables.subjectName = "ENGLISH";
}
}

Single quotes (') denote string literals. Object names, such as table names, should not be surrounded by quotes:
string query = "SELECT question FROM " + GlobalVariables.dbQCode + " WHERE [question_code] = '" + GlobalVariables.questionCode + "' ";
// Quotes removed here --------------^-----------------------------^

Related

C# If statement for SQL

I am using WinForms and I want to use SQL if statement in my code.
Here is a small example. I am using SQL long query and I want to use IF statement to do two different functions. Here is example.
string query =
"SELECT U1.UserID,
U1.FirstName,
U1.LastName,
C1.UserID,
C1.FriendID
FROM USERS U1
INNER JOIN Chat C1 ON U1.UserID = C1.UserID
WHERE C1.UserID = '" + MyName.Uid + "'
AND C1.FriendID = '" + friendid + "'
OR C1.UserID = '" + friendid + "'
AND C1.FriendID = '" + MyName.Uid + "'
ORDER BY C1.ChatID";
There is some more stuff in there. But here is what I need. I know this gonna be wrong, I need someone to help me to write correct if statement.
if (C1.UserID = '" + MyName.Uid + "' and C1.FriendID = '" + friendid + "') {
// some code.
}
You cannot use use SQL Query this way.
First you have to execute your query to get data from database. Once you have it, you can do your if statement to get what you wanted.
And for your if statement you should use Equals to test strings equality.
if (C1.UserID.Equals(someString) && C1.FriendID.Equals(anotherString))
{
//some code.
}

updating data in MySql database table

I am creating a Windows Forms application and now at certain point I need to make a database connection, I have inserted the values to database easily, but now its not updating my data, I am using following query for this purpose:
MySqlCommand sda = new MySqlCommand(#"Update shedulling.tablelayout1 set date = '"
+ date + "',line = " + line + ",col1 = '" + first_textbox.text + "', col2 = '"
+ sec_textbox.text + "',col3_textbox.text = '" + thi_textbox.text
+ "',col4_textbox.text = '" + four + "' where date = '" + date + "' AND line = '"
+ line.ToString() + "' ", conn);
conn is a connection string which is written fine, and date and line are string and integer values send as an argument to this function.
You have missed single quotes in line part. Change it like this line = '" + line + "'.
Also there is one more notable thing in your code: you are trying to find the record in the table that is not exist yet in where clause where date = '" + date + "' AND line = '" + line.ToString() + "' note in this line date and line are the new values not old values so no rows affected in the update query. You should use old values of date and line in the where clause.
Also you should always use parameterized queries. This kind of string concatenations are open for SQL Injection.
Try debugging the code, there must be INSERT statement executing somewhere in your code.
UPDATE: If "line" is integer variable then you need to convert it into string. You have converted it after WHERE clause but not after SET clause.
You may want to post some more code to get exact answer.

Missing operand after '=' operator

I have this line of code which uses a dataview view_1 and I'm trying to filter the datagridview by product_name and its size using the RowFilter.
Here is the code:
view_1.RowFilter = "product_name = '" + cboProduct.Text + "' AND size = " + cboSize.Text + "";
And when I try to run the application it says Missing operand after '=' operator.
So what is that missing operand?
You have a missing white-space at 'AND
So replace
'AND
with
' AND
Is size a string-column or an int-column? If it's a string you need quotation marks around too:
AND size = '" + cboSize.Text + "'";
or even better, use String.Format as others have commented since it insreases readability:
view_1.RowFilter = string.Format("product_name = '{0}' AND size = '{1}'"
, cboProduct.Text
, cboSize.Text);
Write like this
view_1.RowFilter = "product_name = '" + cboProduct.Text + "' AND size = " + cboSize.Text + "";
Missing White space problem
Edit
You can also use string.Format
view_1.RowFilter = String.Format("product_name = '{0}' AND size = {1}", cboProduct.Text,cboSize.Text);
I don't know what is wrong I tried to filter first if the text of cboProduct and cboSize is empty or if no selection has been made and now it's working. Thank you.
Here is the code
if (cboProduct.Text == string.Empty || cboProduct.SelectedIndex == -1 || cboSize.Text == string.Empty || cboSize.SelectedIndex == -1)
{
view_1.RowFilter = string.Empty;
}
else
{
view_1.RowFilter = "product_name = '" + cboProduct.Text + "' AND size = " + cboSize.Text + "";
}
If the variable product_name is having a value that contains a space then the value needs to be wrapped in square brackets in the filter expression:
So,just wrap the variable product_name by pair of square brackets like this
[product_name]
view_1.RowFilter = "[product_name] = '" + cboProduct.Text + "' AND size = " +
cboSize.Text + "";

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.

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