SqlException: Incorrect syntax near the keyword 'AND' - c#

I'm making a management program with C# & SQL Server 2008. I want to search records using Blood Group, District & Club Name wise all at a time. This is what is making prob:
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Table2
WHERE #Blood_Group =" + tsblood.Text + "AND #District =" + tsdist.Text +
"AND Club_Name =" + tscname.Text, Mycon1);
Can anyone tell me what is the correct syntax? Tnx in advance. :)

The correct syntax is to use parametrized queries and absolutely never use string concatenations when building a SQL query:
string query = "SELECT * FROM Table2 WHERE BloodGroup = #BloodGroup AND District = #District AND Club_Name = #ClubName";
using (SqlDataAdapter sda = new SqlDataAdapter(query, Mycon1))
{
sda.SelectCommand.Parameters.AddWithValue("#BloodGroup", tsblood.Text);
sda.SelectCommand.Parameters.AddWithValue("#District", tsdist.Text);
sda.SelectCommand.Parameters.AddWithValue("#ClubName", tscname.Text);
...
}
This way your parameters will be properly encoded and your code not vulnerable to SQL injection attacks. Checkout bobby tables.
Also notice how I have wrapped IDisposable resources such as a SqlDataAdapter into a using statement to ensure that it is properly disposed even in case of an exception and that your program will not be leaking unmanaged handles.

You forgot an AND (and possible an # in front of Club_Name?):
String CRLF = "\r\n";
String sql = String.Format(
"SELECT * FROM Table2" + CRLF+
"WHERE #Blood_Group = {0}" + CRLF+
"AND #District = {1} " + CRLF+
"AND Club_Name = {2}",
SqlUtils.QuotedStr(tsblood.Text),
SqlUtils.QuotedStr(tsdist.Text),
SqlUtils.QuotedStr(tscname.Text));
SqlDataAdapter sda = new SqlDataAdapter(sql, Mycon1);

Related

Insert comma into MS Access database using Visual Studio [duplicate]

This question already has answers here:
Single quote handling in a SQL string
(3 answers)
Closed 6 months ago.
I'm creating an application using Visual Studio 2019, with a connection to an MS Accsess database to add, get, modify and delete values inside the database.
I'm willing to insert a text that could contain a comma, for example : Gousse d'ail. But I know there will be a problem because the string has to be surrounded by commas. So I added a backslash before every extra comma inside the text I'm willing to insert.
The thing is a get an error message saying there is a syntax error, I believe it's because of the backslash.
Here is the message I get :
System.Data.OleDb.OleDbException (0x80040E14) : Syntax error (missing operator) in query expression " 'Gousse d\'ail', unite = 'kg', allergene = False, fournisseurID = 1 WHERE ingrédientID = 40; "
Everything works really well until there is comma.
Here is the method I use to insert into the database:
public void UpdateIngédient(int ingredientID, InfoIngredient ing)
{
string query = "UPDATE Ingrédients ";
query += "SET nom = '" + ing.Nom + "', unite = '" + ing.Unité + "', allergene = " + ing.Allergene + ", fournisseurID = " + ing.Fournisseur;
query += " WHERE ingredientID = " + ingredientID + ";";
OleDbCommand com = new OleDbCommand(query, oleConnection);
com.ExecuteNonQuery();
}
Your query is begging for SQL injection, as well as bugs exactly like the one you've encountered.
If you're doing any work with a SQL table (or OLE in your case) I strongly recommend spending some time to look into SQL injection to understand the risks.
It's very easy to defend against SQL injection and a rewrite of your code is shown below to protect against it.
void UpdateIngédient(int ingredientID, InfoIngredient ing)
{
string query = "UPDATE Ingrédients SET nom = #nom, unite = #unite, allergene = #allergene, fournisseurID = #fournisseur WHERE ingredientID = #ingredientID;";
OleDbCommand cmd = new OleDbCommand(query, oleConnection);
cmd.Parameters.Add(new OleDbParameter("#nom", ing.Nom));
cmd.Parameters.Add(new OleDbParameter("#unite", ing.Unité));
cmd.Parameters.Add(new OleDbParameter("#allergene", ing.Allergene));
cmd.Parameters.Add(new OleDbParameter("#fournisseur", ing.Fournisseur));
cmd.Parameters.Add(new OleDbParameter("#ingredientID", ingredientID));
OleDbCommand com = new OleDbCommand(query, oleConnection);
com.ExecuteNonQuery();
}
This should safeguard against "unexpected" characters in your strings such as the ' character

Can't delete row from single column table

I have problem with the query to delete a row from table(I am using MySQL lite), I'm using data bound comobox to select what to delete but I get this error {"Invalid column name 'Football'."} on executing the command
con.Open();
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = " + cbSelectSport.Text + "", con);
cm.ExecuteNonQuery();
MessageBox.Show("Done");
con.Close();
String concatenation should be avoided in almost every case. You should use parameterized queries whenever possible. You avoid conversions, SQL injection attacks and the code is typically faster because the server can reuse execution plans
Writing a parameterized query is also easier:
using(var con=new SqlConnection(...))
{
con.Open();
var cm = new SqlCommand("DELETE FROM Sports WHERE Sport = #sports", con);
var parameter=cm.Parameters.AddWithValue("#sports",cbSelectSport.Text);
cm.ExecuteNonQuery();
MessageBox.Show("Done");
};
This way the parameter values are passed out of band (ie outside the query) without converting to text. This is extremely useful when you want to pass decimal or date values.
Most people would warn against using AddWithValue because it makes too many assumptions based on its input value that can hurt performance. In this case you can use Add to create the parameter, then set its value, size, precision etc:
var parameter=cm.Parameters.Add("#sports",SqlDbType.NVarChar);
parameter.Size=20;
parameter.Value=cbSelectSport.Text;
Be careful with you syntax.
I don't know the type of the sport column, but I think need to enclose your value in quotes( single or double).
new SqlCommand("DELETE FROM Sports WHERE Sport = \"" + cbSelectSport.Text + "\", con);
or
new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "', con);
You must specify textvalue in single quotation marks ''.
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'", con);
You might want to add the single quote:
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'", con);
You should use parametrized query to prevent SQL Injection attack. Also it will solve your problem. By the way you can just add single quotes to your query.
"DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'"

How to use the wildcard% in mysqlcommand using c#

Please help me guys, my professor has done this before but I forgot how. And if possible I need it right now. How do I use the wildcard % in this code? Thanks in advance!!
MySqlCommand SelectCommand = new MySqlCommand("select * from sms.members where memberFName +' '+ memberLName like'" +cmbmemsched.Text+ "';", myconn);
You'd better use parameterized queries to avoid SQL injection:
MySqlCommand selectCommand = new MySqlCommand(
"SELECT * FROM sms.members WHERE memberFName LIKE #memberFName;",
myconn
);
selectCommand.Parameters.AddWithValue(#memberFName, "%" + cmbmemsched.Text + "%");
In this example, the LIKE statement will look for the search phrase anywhere in the middle of the value. If you want to look for records that start with or end with the specified filter you will need to adapt the % in the parameter.
I'd also more than strongly recommend you wrapping your IDisposable resources such as SQL commands in using statement to ensure that they are properly disposed even if some exceptions are thrown:
using (MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM sms.members WHERE memberFName LIKE #memberFName;", myconn))
{
selectCommand.Parameters.AddWithValue(#memberFName, "%" + cmbmemsched.Text + "%");
}

Syntax error in UPDATE statement OleDb Exception

I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".
Here is the code
OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
CN.Open();
cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where id='" + txtID.Text + "'", CN);
cmd1.ExecuteNonQuery();
CN.Close();
need help please to know what is the error here
I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?
Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere
So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this
string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " +
"[Group]=?, description=? where id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
CN.Open();
cmd1.Parameters.AddWithValue("#p1",txtNAME.Text);
cmd1.Parameters.AddWithValue("#p2",Convert.ToInt32(txtNO.Text));
cmd1.Parameters.AddWithValue("#p3",txtPlace.Text);
cmd1.Parameters.AddWithValue("#p4",txtGroup.Text);
cmd1.Parameters.AddWithValue("#p5",txtdec.Text);
cmd1.Parameters.AddWithValue("#p6",txtID.Text);
cmd1.ExecuteNonQuery();
}
Instead for MySQL you have to use the backticks around the GROUP keyword
string commandText = "Update Mosque Set Name=?, No=?, place=?, " +
"`Group`=?, description=? where id=?"
Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.
I recommend using parameters instead:
cmd1 = new OleDbCommand("Update Mosque Set [Name]=#Name, [No]=#No, [place]=#Place, [group]=#Group, [description]=#Description WHERE id=#ID", CN);
cmd1.Parameters.AddWithValue("#Name",txtNAME.Text);
cmd1.Parameters.AddWithValue("#No",Convert.ToInt32(txtNO.Text));
// etc.

Help me Fix this SQL Statement?

Can someone let me know what is wrong with my SQL Statement and how I can improve it?
da = new SqlDataAdapter("SELECT * FROM Guests"+" WHERE Students.name='" +
byNametextBox.Text + "'", MyConn);
An EXISTS predicate is slightly more efficient than a JOIN if you want only columns from one of the tables. Additionaly - never inject strings into SQL statements like that - you're just begging for SQL Injection attacks, or related crashes errors (Yes, I know it's a Forms application, but the same holds true. If you're searching for a name like "O'Leary", you'll get a crash).
SqlCommand cmd = new SqlCommand("SELECT * FROM Guests WHERE EXISTS (SELECT Id FROM Students WHERE Guests.StudentId = Students.Id And Students.name= #name)", MyConn);
cmd.Parameters.Add("#name", SqlDbType.VarChar, 50).Value = byNametextBox.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
Note: Some people may argue that "SELECT *" is bad, and that you should consider specifying individual column names
You need to worry about SQL Injection. Put simply, SQL Injection is when a user is able to put arbitrary SQL statements into your query. To get around this, either use a Stored Procedure or a Parametrized SQL Query. An Example of a Parametrized SQL query is below:
SqlConnection conn = null;
SqlDataReader reader = null;
//Connection string goes here
string studentName = byNametextBox.Text;
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Guests "+" WHERE Students.name = #name", conn);
SqlParameter param = new SqlParameter("#name", SqlDbType.NVarChar, 50);
param.Value = studentName;
cmd.Parameters.Add(param);
reader = cmd.ExecuteReader();
//Do stuff with reader here
SqlDataAdapter("SELECT Guests.* FROM Guests,Students WHERE Guest.StudentId = Student.Id and Students.name='" + byNametextBox.Text + "'", MyConn);`
You need an Inner Join. I think it would be something like this:
SELECT Guests.* FROM Guests INNER JOIN Students ON Students.name = Guests.name WHERE Students.name = '" + byNametextBox.Text + "'"
Try it:
"SELECT g.*
FROM Guests g
INNER JOIN Students s ON g.StudentId = s.StudentId
WHERE Students.Name = '" + byNametextBox.Text + '"'
Assuming that the field wich relates both tables is StudentId.
Beware that SQL is not the same between different Servers. This statement will work on Sql Server, I don't know in others. Also, beware that you aren't protecting yourself on SQL Injection attacks. You should perform your query with parameters, instead of concatenating strings in the way you are doing it.
This is a simple query that you should know by yourself. You can search for tutorials on Google, but here is a generic introduction.

Categories

Resources