programming for keyword search from database? - c#

Hello I have a table with following columns.
Profile_ID,
Name,
Age,
More_Info_about family,
qualification details,
job details and
partner_preference
I have to search on keyword basis and keyword is to be taken from textbox.
The search result should be in such a way so that if keyword presents in starting, ending and in between the sentence of any of the columns presents in where conditions.
I tried LIKE '" + txtbox_keyword.Text + "'
but is not working properly it is not searching data if keyowrd is present in between sentense.
select (Profile_ID,Name,Age, More_info_about_family,Job_Business_Location_City,Salary
from tblRegistration
WHERE More_info_about_family LIKE '" + txtbox_keyword.Text + "'
OR LIKE '" + txtbox_keyword.Text + "'
OR origin LIKE '" + txtbox_keyword.Text + "'
OR Job_Detail LIKE '" + txtbox_keyword.Text + "' ", con);

Use sqlParameter for except sql injection and you need add %% in your query to search by field.
SqlParameter parameter = new SqlParameter("#keyWord",txtbox_keyword.Text);
select (Profile_ID,Name,Age, More_info_about_family,Job_Business_Location_City,Salary
from tblRegistration
WHERE More_info_about_family LIKE '%#keyWord%'
OR LIKE '%#keyWord%'
OR origin LIKE '%#keyWord%'
OR Job_Detail LIKE '%#keyWord%', con,parameter);

Related

C# query not translating to MYSQL

String query6 = "
SELECT p.*,SUM(L.qty)as sales
FROM product p,purchaseLog L
WHERE L.purchaseDate
BETWEEN '"+ startDate.Value.Date.ToString("yyyy-dd-MM") + "'
AND '"+endDate.Value.Date.ToString("yyyy-dd-MM") +"'
AND p.id=l.itemID GROUP BY p.product_name
ORDER BY sales ASC LIMIT " + " " + " " + count + "";
This is the query that I made in Visual Studio. I tried inputting this query manually without variables in phpmyadmin and it works just fine. But for some reason when I write the query down and pass it to a mysqlcommand and mysqldatareader it doesn't detect the date. The count used not work too. But adding space in between the word "limit" and the count made it work.
Is C# trimming some parts of my queries?
This: 'yyyy-dd-MM' is the wrong format. It must be "yyyy-MM-dd". Ideally you'd even prefix this with the word DATE so as to mark the string as a date literal:
" ... WHERE L.purchaseDate BETWEEN DATE '" + startDate.Value.Date.ToString("yyyy-MM-dd") +
"' AND DATE '" + endDate.Value.Date.ToString("yyyy-MM-dd") + "'... "

Inserting data via C# is inaccessible when queried

I am having a very annoying issue with a program I am currently making. In the program a teacher with admin status can add a user to a students_tbl Table in an SQL database by adding in relevant information. The following code adds a Student to the student_tbl in C#.
string studentAdd = "Insert Into student_tbl(Forename, Surname, SchlYear, InOrOut, Block1, Block2, Block3, Block4, Pword) Values (#forename, #surname, '" + SchlYear + "', '" + inOrOut + "' , '" + Blocks[0] + "', '" + Blocks[1] + "', '" + Blocks[2] + "', '" + Blocks[3] + "', #password)";
SqlCommand studentAddCommand = new SqlCommand(studentAdd, con);
studentAddCommand.Parameters.Add(new SqlParameter("#forename", Forename));
studentAddCommand.Parameters.Add(new SqlParameter("#surname", Surname));
studentAddCommand.Parameters.Add(new SqlParameter("#password", hashedPassword));
studentAddCommand.ExecuteNonQuery();
MessageBox.Show("Student Added Successfully");
con.Close();
The variables added in to the table come from results and are simply just names, integers and bools, nothing complex.
The issue I am having is that this data is inaccessible when trying to log in as a student added via this system. If a user is added manually through SSMS then it works fine. Is this something ridiculously basic I am missing, as if I was to add a user ie. 'Joe Bloggs', and search
Select UserID from student_tbl Where Forename = 'Joe'
It simply finds nothing.
Does anybody have any glaring issues I am missing, or not declaring etc? I am able to provide any more information if it could lead to a solution. Thanks.
According to #Jeroen van Langen comment, try to trim values:
studentAddCommand.Parameters.Add(new SqlParameter("#forename", Forename.Trim()));
studentAddCommand.Parameters.Add(new SqlParameter("#surname", Surname.Trim()));

C# MySQL Error “Column count doesn't match value count at row 1”

MySqlCommand cmd1 =
new MySqlCommand(
"INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES('" + txttoname.Text + "', '" + txttoaddress.Text.Replace("\r\n", "<br />").ToString() + "', '" + txtdistrict.Text + "' , '" + dateTimePicker1.Value.Date.ToString("yyyy-MM-dd") +"', '" + txtfor.Text + "', '" + txtref.Text + "', '" + txttotal.Text + "')", conn);
{
Can I get some help please? Im getting Column count doesn't match value count at row 1 when the command1 is executed.
You should never use SQLs like this. It is prone to SQL Injection attacks. When you use it like yours, one can steal confidential information from database or even delete your tables, data etc. For details please read SQL Injection on wiki
Instead you should use parameterized SQL queries. In that way you are safe from injection attacks and I believe it is much more practical to write sql.
In your case entering single ' char into one of the textboxes will cause your query to get exception. To fix the issue just use prameters.
For your case you can write something like that.
string sqlString = #"INSERT INTO quotedetails (
name,
address,
district,
date,
forto,
refto,
total)
VALUES (
#PAR_name,
#PAR_address,
#PAR_district,
#PAR_date,
#PAR_forto,
#PAR_refto,
#PAR_total)";
MySqlCommand cmd1 = new MySqlCommand(sqlString, conn);
cmd1.Parameters.AddWithValue("PAR_name", txttoname.Text);
cmd1.Parameters.AddWithValue("PAR_address", txttoaddress.Text.Replace("\r\n", "<br />"));
cmd1.Parameters.AddWithValue("PAR_district", txtdistrict.Text);
cmd1.Parameters.AddWithValue("PAR_date", dateTimePicker1.Value.Date);
cmd1.Parameters.AddWithValue("PAR_forto", txtfor.Text);
cmd1.Parameters.AddWithValue("PAR_refto", txtref.Text);
cmd1.Parameters.AddWithValue("PAR_total", txttotal.Text);
Please note that I use prefix PAR_ for my sql parameters, it is just a convention you can use that or skip PAR_ prefix does not matter and it is all about naming habits.
Additionaly; in a parameterized query, you don't need to convert all your values to string. You can use DateTime for your date field or you can pass int variable without using ToString() as you do before.
On the face of it, this happens when the number of values are more or less than columns provided.
From your statement, this does not seem to be the case. BUT since you are providing uielements directly into insert statement (Textbook case of SQL Injection), I am guessing there is a single quote ' in any of your ui elements, which breaks your insert statement.
MySqlCommand cmd1 = conn.CreateCommand();
cmd1.CommandText = "INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES('" + txttoname.Text + "', '" + txttoaddress.Text.Replace("\r\n", "<br />").ToString() + "', '" + txtdistrict.Text + "', '" + dateTimePicker1.Value.Date.ToString("yyyy-MM-dd") +"', '" + txtfor.Text + "', '" + txtref.Text + "', '" + txttotal.Text + "')";
Using SQL parameters will save you from lots of trouble as well as SQL injection.I am quite sure that if you use parameters your problem will be resolved:
MySqlCommand cmd1 = new MySqlCommand( "INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES(#name,#address,#district,#date,#forto,#refto,#total)", conn);
cmd1.Parameters.AddWithValue("#name",txttoname.Text);
cmd1.Parameters.AddWithValue("#address",+ txttoaddress.Text.Replace("\r\n", "<br />").ToString());
cmd1.Parameters.AddWithValue("#district",txtdistrict.Text);
...

SQL LIKE query to C# code

I need to use the following query in my C# code:
SELECT AVG(Percent)
From Table1
Where code Like "Sport" and Year Like"2011" and Sitting Like"June";
I did it like this:
"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE " + comboBoxSubject.Text +
"AND Year LIKE "+dateTimePicker1 +" AND Sitting LIKE June"
but i get an exception probably because the parameters are extracted from different controls and are not placed in inverted commas.
Can anyone help me ?
ANSWER
That is the query that worked for me:
"SELECT AVG(Percent) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text + "' AND Year LIKE '" + dateTimePicker1.Value.Year + "' AND Sitting LIKE 'June'"
Supposing you use SQLite, because you don't mention any database. This is how you can avoid SQL injection.
var selectCommand = new SQLiteCommand("#SELECT AVG (PERCENT)
FROM TABLE1
WHERE CODE LIKE #sport AND YEAR LIKE #year AND SITTING LIKE #month");
selectCommand.Parameters.AddWithValue("#sport", sportParameter);
selectCommand.Parameters.AddWithValue("#year", yearParameter);
selectCommand.Parameters.AddWithValue("#month", monthParameter);
There are three problems.
There's no space after the code value and AND
There are missing single quotes between values
The wildcard symbol (%) is missing from the SQL LIKE statements
It depends what kind of project you are working on but often I find it is much easier to spot syntax errors and missing spaces by printing the end query out. For example, below is a console application that does this.
static void Main(string[] args)
{
const string code = "Sport";
const string year = "2011";
Console.WriteLine("SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE '%" + code + "%' AND Year LIKE '%" + year + "%' AND Sitting LIKE '%June%'");
}
Use single quotes for character fields.
"SELECT AVG(Percentage) FROM MasterTable WHERE Code LIKE '" + comboBoxSubject.Text +
"' AND Year LIKE '" + dateTimePicker1 + "' AND Sitting LIKE 'June'"
Use % and ' and please consider to use parameters:
SELECT AVG(Percentage) FROM MasterTable WHERE (Code LIKE '%' + #text + '%')
MySqlCommand cmd = new MySqlCommand("SELECT Employee_No, Image, Last_Name, First_Name, Middle_Name, Suffix, Sex, Birthdate, Contact_No, Address, Username FROM user_tbl WHERE Employee_No LIKE '%" + searchemployeeno + "%' OR Last_Name LIKE '%" + searchemployeeno + "%' ", SQLConn.conn);

Question about adding to database from text entered into textbox

I have an app that displays data from a sql database in a datagrid. I am adding a feature that will allow a user to add a new item to this datagrid. I will have an Add button in the app that when clicked, will open a new window where all the info will be added. After the user inputs the info into the text boxes and clicks save, that info gets saved to the database. This will require inserting data into two separate tables that are related. The first table is ItemDescriptor and the other table is Accessories. The id for ItemDescriptor has to be put into the Accessories table as ItemDescriptorID. I have tried to do two separate insert queries but cant figure out how to get the id from ItemDescriptor into the Accessories table programatically. Sorry, I know this might be a little confusing. Let me know if more info is needed. Thanks
_dbAccess.ExecuteNonQuery("INSERT INTO ItemDescriptor (id, Model, Brand, DeviceName, Type, Notes) VALUES ('" + System.Guid.NewGuid() + "', '" + tbModel.Text + "', '" + tbBrand.Text + "', '" + tbDeviceName.Text + '", '" + cmbType.SelectedValue + "', '" + tbNotes.Text + "')");
_dbAccess.ExecuteNonQuery("INSERT INTO Accessories (id, ItemDescriptorID, StorageRoomCount, OnHandCount, HiBayCount) VALUES ('" + System.Guid.NewGuid() + "', '" +
and thats about as far as i got...not sure how to get the ItemDescriptorID in there from the first query.
First, please please please use parameterized queries when dealing with user-supplied input. That string concatenation stuff is just asking for a SQL injection attack.
Second of all, if you're using SQL Server, you can use something like ##IDENTITY to get the identity field after insertion. There's something comparable on all systems, so if you let us know what you're using we can point you in the right direction.
I'm assuming that you're using SQL Server and that ItemDescriptor.id is an identity column; correct?
If you execute the following command immediately after your initial insert statement, it will return the value of the most recently generated identity:
var newID = _dbAccess.ExecuteScalar("SELECT Scope_Identity()");
You can use newID to construct your second insert statement.
One caveat: The SELECT Scope_Identity() statement must be executed on the same connection instance as the initial insert statement. So ensure that you're not closing and reopening your connection between statements. If this seems to be a problem, you can actually combine your insert and select statements into a single command; e.g.:
var newID = _dbAccess.ExecuteScalar("INSERT [all your code here]; SELECT Scope_Identity();");
Good luck!
Check out this site about Getting the identity of the most recently added record
I figured out a way to make it work. I just made the guid an object and then used it as a variable and that worked. thanks for all the suggestions.
Guid guid = System.Guid.NewGuid();
if (_dbaccess != null)
{
_dbAccess.ExecuteNonQuery("INSERT INTO ItemDescriptor (id, Model, Brand, DeviceName, Type, Notes) VALUES ('" + guid + "', '" + tbModel.Text + "', '" + tbBrand.Text + "', '" + tbDeviceName.Text + '", '" + cmbType.SelectedValue + "', '" + tbNotes.Text + "')");
_dbAccess.ExecuteNonQuery("INSERT INTO Accessories (id, ItemDescriptorID, StorageRoomCount, OnHandCount, HiBayCount) VALUES ('" + System.Guid.NewGuid() + "', '" + guid + "', '" + tbStorageRoom.Text + "', '" + tbOnHand.Text + "', '" + tbHiBay.Text + "')");
}

Categories

Resources