exception System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.' - c#

Trying to fill a ComboBox after I insert a value in another TextBox. It keeps returning:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
public void carrega_status()
{
string sql2 = "select * from tb02_alarme WHERE tb02_desc =" + txtdescala + " ;";
SqlConnection conn1 = Conexao.ObterConexao();
SqlDataAdapter da2 = new SqlDataAdapter(sql2, conn1);
DataTable resultado = new DataTable();
resultado.Clear();
txtstatus.DataSource = null;
da2.Fill(resultado);
txtstatus.DataSource = resultado;
txtstatus.ValueMember = "tb02_class";
txtstatus.DisplayMember = "tb02_class";
txtstatus.SelectedItem = "";
txtstatus.Refresh();
}
The error presents itself on da2.Fill(resultado);.

try this solution that works with me :
string sql2 = "select * from tb02_alarme WHERE tb02_desc ='" + txtdescala + "' ;";

It is never a good idea to leave yourself open to SQL injection. Especially if you are just learning, you should learn the correct way from the start - instead of learning the hard way.
Here is a simple tutorial on how to do this.
People can answer your question all they want, but it won't help you in the long run. With all the comments telling you to use parameters, you should really heed the warning, as all of these people are the experts trying to help you!

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

Additional information: Incorrect syntax near 'VALUE'

I m a beginning Developer, I m still studying and currently im stuck on a error. I'm learning a new technic on how to make proper sqlconnections.. but seems as i cannot find out whats wrong.
This is a simple program where, the user is scanning a bar code to fill a textbox. And depending on that value. Rest of the textboxes will be filled in.
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code .Additional information: Incorrect syntax near 'ProductBarcode'.
This is my code right now:
protected void PBarcodeTxt_TextChanged(object sender, EventArgs e)
{
string cmd = "SELECT ProductNaam, ProductPrijs, ProductOmschrijving, ProductBarcode" +
"FROM Producten" +
"WHERE ProductBarcode LIKE '#Barcode'";
using (SqlConnection connection = new SqlConnection(cstring))
{
SqlCommand command = new SqlCommand(cmd, connection);
command.Parameters.Add("#Barcode", SqlDbType.VarChar, 50).Value = PBarcodeTxt.Text;
try
{
connection.Open();
SqlDataReader rdr = command.ExecuteReader();
rdr.Read();
PNaamTxt.Text = (rdr["ProductNaam"].ToString());
POmschrijvingTxt.Text = (rdr["ProductOmschrijving"].ToString());
PPrijsTxt.Text = (rdr["ProductPrijs"].ToString());
// PBarcodeTxt.Text = (rdr["ProductBarcode"].ToString());
}
finally
{
connection.Close();
}
Thank you for your time and effort.
In your command you are missing a number of spaces, try the following (notice the spaces before FROM and WHERE:
string cmd = "SELECT ProductNaam, ProductPrijs, ProductOmschrijving, ProductBarcode" +
" FROM Producten" +
" WHERE ProductBarcode LIKE '#Barcode'";
When you concatenate strings in this way you need to explicitly enter new lines and spaces, what you had before when concatenated would actually be:
string cmd = "SELECT ProductNaam, ProductPrijs, ProductOmschrijving, ProductBarcodeFROM ProductenWHERE ProductBarcode LIKE '#Barcode'";

Data Type Mismatch when evaluating Access Calculated Fields in Visual c# using Microsoft Access Database Engine

I have a OleDbCommand in a Visual Studios c# windows forms project, and I am trying to select the name of every item in my Access Table Stock where the value of a calculated field in that table is less than one. The result type of the calculated field in Access is set to decimal, and the code looks as if it should work, but for whatever reason it doesn't. Could you help me?
Here is my code:
loginForm.connection.Open();
stockLowString = "";
var checkStockLowCommand = new OleDbCommand("SELECT stockName FROM Stock WHERE (stockLowCalculation < '" + Convert.ToDecimal(1) + "')",loginForm.connection);
OleDbDataReader checkStockLowReader = checkStockLowCommand.ExecuteReader();
while (checkStockLowReader.Read())
{
stockLowString = stockLowString + checkStockLowReader.GetString(0) + " ";
}
if (stockLowString != "")
{
MessageBox.Show("There are some Stock Items that are low, these are" + Environment.NewLine + stockLowString);
}
loginForm.connection.Close();
The error occurs on the line
OleDbDataReader checkStockLowReader = checkStockLowCommand.ExecuteReader();
Thanks in advance for your help.
Problem Solved, or at least avoided. I just put the calculation in the Command rather than use a calculated field.
The question is still valid though, as I didn't solve it.
Open the database and check the type of the field "stockLowCalculation" it's most likely not decimal.. I suggest you rework your query and make it parametrized. This way you would evade most of the possible data type mismatch errors.
string conS ="..."; // connection string
var param = 1;
using (var connection = new OleDbConnection(conS))
{
string queryString = "SELECT stockName FROM Stock WHERE stockLowCalculation < #var"
var cmd = new OleDbCommand(queryString, connection);
cmd.Parameters.Add(new OleDbParameter("#var", param));
connection.Open();
OleDbDataAdapter adapt = new OleDbDataAdapter(cmd);
}

SqlException: Incorrect syntax near the keyword 'AND'

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);

Cannot figure out how to fix syntax error (missing operator) in query expression error in C#

I'm having an issue with an error written above and cannot find a exact way to fix it.
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("Select count(*) from [contractors$] where " + category + " like '*#name*'", eh.Connection);
dataAdapter.SelectCommand.Parameters.Add("#name", OleDbType.VarChar).Value = "*" + name + "*";
OleDbCommand command = dataAdapter.SelectCommand;
OleDbDataReader reader = command.ExecuteReader();
The exact error is..
Syntax error (missing operator) in query expression 'like '#name''.
I've also already looked for solutions to this problem and have attempted to adapt them to try to get this work work, but with no luck(the one above was one of the attempts)
Much thanks in advance!
Ok, so I have now change the code to this..
OleDbDataAdapter dataAdapter = new OleDbDataAdapter("Select count(*) from `contractors$` where " + category + " LIKE #name", eh.Connection);
dataAdapter.SelectCommand.Parameters.Add("#name", OleDbType.VarChar).Value = "%" + name + "%";
OleDbCommand command = dataAdapter.SelectCommand;
OleDbDataReader reader = command.ExecuteReader();
But I am still getting the same error.
A parameter cannot be contained inside an SQL string literal. Use concatenation to build the string:
"... LIKE ('%' + #name + '%') ..."
Update
It seems that the value of category was null or empty, creating an invalid SQL statement:
Select count(*) from [contractors$] where like '#name'
^^^ no category here

Categories

Resources