Additional information: Incorrect syntax near 'VALUE' - c#

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'";

Related

Invalid Column name asp

This is my first time creating a web api from scratch and I'm trying to get a selected value in a drop down bow to trigger an sql search and make the appropriate item appear in a text box. below is the relevant code
protected void btnRetrieve_Click(object sender, EventArgs e)
{
try
{
string pNameTemp = DropDownList1.SelectedValue;
myConnection.Open();
string query = ("SELECT sName from [dbo].[Table] WHERE (pName LIKE " + pNameTemp + ")");
SqlCommand sqlCmd = new SqlCommand(query, myConnection);
txtSkill.Text = sqlCmd.ExecuteScalar().ToString();
myConnection.Close();
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
it seems to search the correct name but when it comes to updating the txtSkill, I get the exception 'invalid column name' pop up, are there any obvious reasons as to why this is happening that i'm missing? any advice would be appreciated
In fact, you are missing '' for the parameter of the query.
Try to use this query.
SqlCommand sqlCmd = new SqlCommand(#"SELECT sName from [dbo].[Table] WHERE pName LIKE '{pNameTemp}'", myConnection);
But I recommend you to use SqlParameter in C# to avoid SQL Injection
SqlCommand com = new SqlCommand("SELECT sName from [dbo].[Table] WHERE pName LIKE #field", myConnection);
myConnection.Parameters.AddWithValue("#field", pNameTemp);
But normally, when we use LIKE, we should put in % because it gives all results contains keyword. LIKE without % doesn't make sense. So :
SqlCommand com = new SqlCommand("SELECT sName from [dbo].[Table] WHERE pName LIKE #field", myConnection);
command.Parameters.AddWithValue("#field", "'%" + pNameTemp + "%'");
There are some options in the LIKE clause:
%: The percent sign represents zero, one, or multiple characters
_ The underscore represents a single character

sql syntax error - not able to append string to a database

I am currently working on a dummy project in which I am making a login screen. I don't have any big intentions with the project, beside learning some C# and sql.
I am currently trying append a new user to the database which contains each username and their password, but I am for some reason getting an error message.
The entry written in the textbox should be stored in the database, but for some reason is this not happening..
I am getting an error stating I have a syntax error which I am not sure i understand.
private void create_user_username_box_Leave(object sender, EventArgs e)
{
// Add user/password to database when when someone leaves the area.
using (DbConnection connection = new SqlConnection(#"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
{
connection.Open();
using (DbCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
{
command.Connection = connection;
command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
}
}
}
Do not do the following, ever
"INSERT INTO [dbo].[information] (id,password)
VALUES (" + someStringVariable + "," + someOtherStringVariable + ")"
Just think about what you're doing here - you're putting whatever text the user entered directly into your query string. This is the easiest way to have your database dropped or all the information it contains stolen.
Instead, use prepared statements
var commandText = "INSERT INTO [dbo].[information] (id,password) VALUES (#Username, #Password)"
using (var command = new SqlCommand(commandText, connection))
{
command.Parameters.Add("#Username", SqlDbType.VarChar).Value = create_user_username_textbox.Text
command.Parameters.Add("#Password", SqlDbType.VarChar).Value = create_user_password_textbox.Text
command.ExecuteNonQuery();
}
You should also strongly consider NOT storing passwords in plain text
Updated with suggestion to replace Parameters.AddWithValue - obviously if the column type on your database is different, set it accordingly
The values are strings so the resulting SQL command text should enclose them within single quotes.
VALUES ('"+create_user_username_textbox.Text+"','"...
However, you should really parameterise the query to prevent the potential for Sql injection attacks.
Change the string to:
VALUES (#id,#pw)"))
Add parameters to the command:
command.Parameters.Add(new SqlParameter("#id", create_user_username_textbox.Text));
command.Paramaters.Add(new SqlParameter("#pw", create_user_password_textbox.Text));
try this -
private void create_user_username_box_Leave(object sender, EventArgs e)
{
// Add user/password to database when when someone leaves the area.
using (SqlConnection connection = new SqlConnection(#"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
{
command.Connection = connection;
command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
}
}
}

No value given for one or more required parameters error while deleting in database

Every time I execute a DELETE query on my database, the following error results:
No value given for one or more required parameters
I check the names but still have the error. Below is the code used to execute the query:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "delete FROM Accounts WHERE Id_No = " + IdNoBox.Text + "";
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Successfully Deleted");
this.Close();
connection.Close();
Assuming Id_No to be string, it should be enclosed in single quotes.Otherwise, it will be considered as a parameter.
the query should string query = "delete FROM Accounts WHERE Id_No = "'" + IdNoBox.Text + "'";
To address the specific question being asked, if Id_No is a character based, there should be single quotes around it. For readability, consider the following syntax.
string query = string.Format("delete FROM Accounts WHERE Id_No = '{0}' ", IdNoBox.Text);
Also note that the connection/command should be disposed of properly, including the cases where an exception occurs. An easy way to do this is with the using clause. See below.
using (var connection = new OleDbConnection())
using (var command = new OleDbCommand(){Connection = connection,CommandText = query})
{
connection.Open();
command.ExecuteNonQuery();
}
MessageBox.Show("Successfully Deleted");

not able to load odbcdatareader to a datatable

I am using an Informix db, and I am trying to get data for a specific item and store it in a datatable.
I checked the following:
1) connection string looks good
2) the connection is able to open
3) I used the same connection string from the web.config on a dataset creating a table adapter and it is able to retrieve the record.
This is the code I am using:
var connectionstring = ConfigurationManager.ConnectionStrings["TestDataTable"].ConnectionString;
OdbcConnection con = new OdbcConnection(connectionstring);
//con.ConnectionString = connectionstring;
if (TxtItem.Text != hold_item)
{
con.Open();
OdbcCommand cmd = new OdbcCommand(#"Select t_item,t_idsc,t_upct,
t_item_upc,t_ctyp,t_citg,
t_best,t_disp,t_mold,t_csel
from informix.tsckcm907
where t_item = " + stitem, con);
OdbcDataReader myReader = cmd.ExecuteReader();
DataTable testdt = new DataTable();
testdt.Load(myReader);
foreach (DataRow row in testdt.Rows)
{
lbldesc.Text = row["t_idsc"].ToString();
Spanish_Item();
{
DropDownList2.SelectedIndex = 1;
object stlanguage = 1;
hold_language = Convert.ToString(stlanguage);
TxtBestBefore.Text = row["t_best"].ToString();
holdbest = Convert.ToInt16(TxtBestBefore.Text);
}
}
myReader.Close();
myReader.Dispose();
cmd.Dispose();
con.Close();
con.Dispose();
}
in debug mode my error occurs at the OdbcDataReader line:
error message:
An exception of type 'System.Data.Odbc.OdbcException'
occurred in System.Data.dll but was not handled in user code
Additional information: ERROR [42000] [Informix]
[Informix ODBC Driver][Informix]A syntax error has
occurred.
If your Informix ODBC driver says: "A syntax error has occurred" then you have to check your SQL statement:
"Select t_item,... from informix.tsckcm907 where t_item = " + stitem
I think that something is wrong with stitem. We don't know what type and value it is, but if its type is some kind of string or date then it may be in the wrong form. Easiest way is to extract full SQL statement (simply print it before execution) and use it with some database editor (for example db_access from Informix). Then make it work in SQL editor and transform stitem variable into acceptable form (add quotes, escape internal quotes, escape special characters etc.)
I also recommend use of PreparedStatement that separates your query from data. This way you do not need to worry about stitem form. No quotes, no escaping, just place holder in query string and value added separately.
I don't use C# but I see that C# can work with preapred statements with unnamed parameters:
cmd.CommandText = "SELECT ... FROM ... WHERE t_item = ?";
cmd.Parameters.Add("#t_item", ObdcType.VarChar, 200).Value = t_item;
or with named parameters:
cmd.CommandText = "SELECT ... FROM ... WHERE t_item = #t_item";
cmd.Parameters.Add("#t_item", ObdcType.VarChar, 200).Value = t_item;
I use unnamed parameters from ODBC so Informix driver can work with such parameters but you will have to check it yourself with C#.

MySqlCommand.ExecuteScalar() not returning anything

When I run the following code:
query = "select count(*) from table where name = '?name'";
MySqlConnection connection =
new MySqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
connection.Open();
MySqlCommand command = new MySqlCommand(query,connection);
command.Parameters.Add("?name", name);
Int32 number = command.ExecuteScalar();
number is always zero, even when cast to an int.
I have tried converting it to int64, no dice. I have tried command.Prepare(). I have tried using Convert.ToInt32() and every other variation. I have tried just about everything under the sun including quoting verbatim what this suggests and I get no dice. Trying to cast the object as an integer, as a long, as an int32, none of this seems to work. These results are always 0 or cause a MySQL error.
EDIT: Stack overflow will not format that code properly in code tags, i apologize
The reason for that is because the parameter is enclose with single quote thus making it a string. Remove it and it will work,
query = "select count(*) from table where name = #name";
MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ToString());
connection.Open();
MySqlCommand command = new MySqlCommand(query,connection);
command.Parameters.Add("#name", name);
for better code,
use using for proper object disposal
using try-catch block for proper handling of exceptions
code snippet,
query = "select count(*) from table where name = #name";
string connString =ConfigurationManager.ConnectionStrings["mydb"].ToString();
using(MySqlConnection connection = new MySqlConnection(connString))
{
using(MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.Add("#name", name);
try
{
connection.Open();
// other codes
}
catch(MySqlException ex)
{
// do somthing with the exception
// don't hide it
}
}
}

Categories

Resources