I am getting an error
Incorrect syntax near '('
I am updating a product from the database when a specific product code is entered.
How can this be done?
// Update product with supplier code entered
DialogResult dr = MessageBox.Show("Are you sure you want to update this product?", "Update Product Details", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
try
{
using (SqlConnection SQLcon = new SqlConnection("Data Source = .\\SqlExpress;" + "Initial Catalog=NCAShop;" + "Integrated Security=True;"))
{
SQLcon.Open();
using (SqlCommand addProduct = new SqlCommand("UPDATE dbo.[NCAProduct] (ProductName, SupplierCode, Cost, RetailPrice, Quantity, BestBefore) VALUES ('" + txtUPProductName.Text + "', " + txtUPSupplierCode.Text + ", " + txtUPCost.Text + ", " + txtUPRetail.Text + ", " + txtUPQuantity.Text + ", #date) WHERE ProductCode = " + txtUPProdCode.Text, SQLcon))
{
addProduct.Parameters.Add("#date", SqlDbType.DateTime).Value = bestBeforeDTP.Value.Date;
addProduct.ExecuteNonQuery();
}
}
MessageBox.Show("This product has been successfully added to the database!");
}
catch (Exception error2)
{
MessageBox.Show(error2.ToString());
}
}
else if (dr == DialogResult.No)
{
// Program will continue if user selects 'No'
}
You need to use to correct syntax for an SQL update. The syntax is:
UPDATE table SET column = value, ... WHERE ...
You're mixing it with the INSERT syntax, which is
INSERT INTO Table (Column, ...) VALUES (Value, ...)
I suppose that you actually want to do an INSERT anyway. In that case, replace the word UPDATE in your query with INSERT INTO and you should be fine.
PS: Oh and please - use parameters for all the values, not just the date.
Use proper query formatting sometimes '[ ]' these brackets create an error while executing the query in the DB and please use a proper conversion for specific database types. To prevent sqlinjection attacks I used a SqlCommandParameter for each user provided input. You can use the query given below:
string query = #"UPDATE dbo.[NCAProduct] (
[ProductName],
[SupplierCode],
[Cost],
[RetailPrice],
[Quantity],
[BestBefore]) VALUES
(#txtUPProductName,
#txtUPSupplierCode,
#txtUPCost,
#txtUPRetail,
#txtUPQuantity,
#date)
WHERE [ProductCode] = #txtUPProdCode";
using (SqlCommand addProduct = new SqlCommand(query, SQLcon))
{
addProduct.Parameters.AddWithValue("#date", SqlDbType.DateTime).Value = bestBeforeDTP.Value.Date;
addProduct.Parameters.AddWithValue("#txtUPProductName", txtUPProductName.Text);
addProduct.Parameters.AddWithValue("#txtUPSupplierCode", Convert.ToInt32(txtUPSupplierCode.Text));
addProduct.Parameters.AddWithValue("#txtUPCost", Convert.ToInt32(txtUPCost.Text));
addProduct.Parameters.AddWithValue("#txtUPRetail", Convert.ToInt32(txtUPRetail.Text));
addProduct.Parameters.AddWithValue("#txtUPQuantity", Convert.ToInt32(txtUPQuantity.Text));
addProduct.Parameters.AddWithValue("#txtUPProdCode", Convert.ToInt32(txtUPProdCode.Text));
addProduct.ExecuteNonQuery();
}
Convert text to int64 or double if you are using bigint data type in database.
Related
My code to populate a ComboBox with unique value list of the items in an SQL database column is not functioning as required. It is simply mirroring the list of items in the column, even if there are multiple identical entries. I am new to coding, please help a solution for this in English.
void Fillcombo()
{
if (sqlconf2.State == ConnectionState.Closed)
sqlconf2.Open();
//after connection is open, using following "if" code to check uniqueness of Step
string query = "Select [Animal ID] from ExpData where SystemUser = '" + textBox15.Text.Trim() + "' ;" ;
SqlCommand cmd = new SqlCommand(query, sqlconf2);
try
{
SqlDataReader myda = cmd.ExecuteReader();
while (myda.Read())
{
string AnIDs = myda.GetString(0).ToString();
comboBox4.Items.Add(AnIDs);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sqlconf2.Close();
}
}
Change your query to this
string query = "Select Distinct [Animal ID] As AnimalId from ExpData
where SystemUser = '" + textBox15.Text.Trim() + "' Order By [Animal ID] ;" ;
And for the smart guys I recommend you to use a parameter instead of textBox15.Text
I've had an ASP.NET page that had worked for quite a while, up until recently. The page contains a single text box (TextBox1) and a submit button. When you input (or scan) a number into the field and submit it, if the record exists in the database and hasn't been submitted before, it adds a date/time stamp to another column and gives the user feedback that it's been recorded. If the record exists and already had a date/time stamp, it doesn't change anything but gives the user feedback that the record already has been input or scanned. If the record doesn't exist, it gives the user feedback that there is no such record.
This all worked fine when I was inputting numerical values. Now, the numeric values have changed to alphanumeric and I'm getting and error. Anytime I input a value that is alphanumeric, I get an
Incorrect syntax near 'x'
error that refers to line 35:
using(SqlDataReader reader = command.ExecuteReader())
My entire code from my aspx.cs file is below. Any suggestions are greatly appreciated!
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
try
{
connection.Open();
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + " and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
if(reader.HasRows)
{
string sql2 = #"UPDATE [products] SET date=#Value2 where PRODUCT_ID=#Value1";
using (SqlCommand command2 = new SqlCommand(sql2, connection))
{
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
command2.ExecuteNonQuery();
}
pageBody.Attributes.Add("bgcolor", "#9aff8e");
Label1.Text = "Item " + TextBox1.Text + " Recorded!";
TextBox1.Text = "";
}
else
{
reader.Close();
string sql3 = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = " + TextBox1.Text + "";
using(SqlCommand command3 = new SqlCommand(sql3, connection))
{
using(SqlDataReader reader2 = command3.ExecuteReader())
{
if (reader2.HasRows)
{
pageBody.Attributes.Add("bgcolor", "#fbff8e");
Label1.Text = "Item " + TextBox1.Text + " Already Shipped!";
TextBox1.Text = "";
}
else
{
pageBody.Attributes.Add("bgcolor", "#ff8e8e");
Label1.Text = "Item " + TextBox1.Text + " Not Found!";
TextBox1.Text = "";
}
}
}
}
}
}
}
finally
{
if(connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
}
First of all: Never do string concatenation for SQL with user input. It opens up risk for Sql Injection which can destroy your database.
The error is due to the change in datatype of PRODUCT_ID from number to string. Add ' to fix the error.
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = '#Value1' and DATE is null";
using(SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#Value1", TextBox1.Text);
...
}
I hope since you are inputing a alphanumeric field, you have to use. (Note the quotes beside textbox text )
string sql = #"SELECT PRODUCT_ID from PRODUCTS where PRODUCT_ID = '" + TextBox1.Text + "' and DATE is null";
As you are saying its a alphanumeric field, you have to search your product_id by enclosing it as a string.
(Assuming datatype of PRODUCT_ID in your table is varchar. If your datatype is not VARCHAR, you might still see an error )
And yes, As #Faruq mentioned, make sure to update your code to use command parameters to avoid SQL injections.
Change:
PRODUCT_ID = " + TextBox1.Text + "
TO:
PRODUCT_ID = '" + TextBox1.Text + "'
You need to quote the text, so abc should be 'abc' when it gets to the database.
EDIT
i changed the code so i am using:[" + Time1 + "] instead of the parameter. This works for the first time, but when the time increases by 0.5, it stays false. The for loop is working as i tried a MessageBox.Show("" + Time1 + ""); inside the for loop.
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
try
{
SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");
cn.Open();
SqlCommand Command = new SqlCommand("INSERT INTO Slots ([Date],[RoomID],[" + Time1 + "]) Values (#date,#room,1)", cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
try
{
cn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
You have a # before your 3rd column (time).
When you add a parameter you need to add the #.
On your insert statement you are trying to insert true as a boolean into the time column.
SqlCommand Command = new SqlCommand("INSERT INTO Slots (Date,RoomID,time) " + "Values (#date,#room,#time)", cn);
Command.Parameters.AddWithValue("#date", date);
Command.Parameters.AddWithValue("#room", rooms_combo.SelectedValue);
Command.Parameters.AddWithValue("#time", Time);
EDIT After comments. Try this:
SqlCommand Command = new SqlCommand("INSERT INTO Slots (Date,RoomID,[" + Time1 + "]) " + "Values (#date,#room,#time)", cn);
Command.Parameters.AddWithValue("#date", date);
Command.Parameters.AddWithValue("#room", rooms_combo.SelectedValue);
Command.Parameters.AddWithValue("#time", true);
You're listing a variable as a column name (#time)
EDIT
Right here:
INSERT INTO Slots (Date, RoomID, --->>> #time <<<--- DANGER WILL ROBINSON, DANGER
To fix it, you need to either change it to a column name from your table, or else get rid of it.
So something like this, for example:
INSERT INTO Slots (Date, RoomID, time)
You can't include a variable in your column list, I presume you wanted that #Time to be in the value list about where that true is.
EDIT: To inject the time as a column name, do some C# string manipulation:
SqlCommand Command = new SqlCommand("INSERT INTO Slots (Date, RoomID, [" + time + "]) Values (#date, #room, 1)", cn);
EDIT again: true is not a T-SQL keyword, T-SQL bit columns have values 1 or 0
Now you don't want to add time as a parameter to the query.
What I am trying to do:
Execute DML statements into database (SSCE) using Datagridview and command buttons.
The Problem:
I am getting exact same error as this post: SQL [Error]: There was an error parsing the query. [ Token line number = 1,Token line offset = 44,Token in error = - ]
Based on those answers and others available on the web, I have validated the query string, yet not able to solve it. There's also one other aspect I have doubts.
private void button2_Click(object sender, EventArgs e)
{
using (SqlCeConnection CONN = new SqlCeConnection("Data
Source=LocalDBSSCompactEdition.sdf;"))
{
SqlCeCommand comm = new SqlCeCommand();
comm.Connection = CONN;
CONN.Open();
int i = dataGridView2.Rows.Count-1;
String queryString = #"INSERT INTO tblEmployee VALUES ("
+ dataGridView2.Rows[i].Cells["E_ID"].Value + ", "
+ dataGridView2.Rows[i].Cells["FirstName"].Value + ", "
+ dataGridView2.Rows[i].Cells["LastName"].Value + ", "
+ dataGridView2.Rows[i].Cells["DeptID"].Value + ");";
comm.CommandText = queryString;
comm.ExecuteNonQuery();
}
}
1) E_ID column is IDENTITY(auto-increment). However I got an error, saying that I must include all the columns in DataGridview to match to the database table. Could this be the issue that I am getting or could it be my syntax?
2) I want to insert new rows/updates/deleted rows from Datagridview to the database table using a button click event. Is this the efficient way of doing so?
Some insights to the right direction is appreciated.
I managed to get it solved. I don't believe in answering my own-question. Just added the answer hoping for someone else's reference in the future.
1) i variable was referring to an empty row in the datagridview...Hence the values to be inserted were null and these columns are specified NOT NULL...
2) First rule was to follow the usual INSERT statement when ID column is auto-increment. So I specify the columns that I want to insert data for.
3) The data that I was entering were not quoted to treat as String. Fixed.
private void button2_Click(object sender, EventArgs e)
{
using (SqlCeConnection CONN = new SqlCeConnection("Data Source=LocalDBSSCompactEdition.sdf;"))
{
CONN.Open();
SqlCeCommand comm = CONN.CreateCommand();
int i = dataGridView2.Rows.Count-1;
String queryString = #"INSERT INTO tblEmployee (FirstName, LastName, DeptID) VALUES ('"
+ dataGridView2.Rows[5].Cells["FirstName"].Value + "','"
+ dataGridView2.Rows[5].Cells["LastName"].Value + "',"
+ dataGridView2.Rows[5].Cells["DeptID"].Value + ");";
comm.CommandText = queryString;
comm.ExecuteNonQuery();
CONN.Close();
}
}
I have a database with some columns named UPC title Description and Quantity. i am trying to do a check to see if a UPC number already exists in the column and IF IT DOES then update the quantity of that entry by 1 here is what i have so far:
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(#upc, #title, #description, #quantity)";
MySqlCommand upcCheck = connection.CreateCommand();
upcCheck.CommandText = "Select COUNT (*) FROM tableName WHERE " +
"(upc=#upc) LIMIT 1";
upcCheck.Parameters.AddWithValue("#upc", upc.Text); //Checks for duplicate UPCs
MySqlDataReader check = upcCheck.ExecuteReader();
if( check.Read() != false)
{
command.Parameters.AddWithValue("#quantity",++); //not sure how to word it right
}
command.Parameters.AddWithValue("#upc", upc.Text); //adding parameters SAFELY to the statement
command.Parameters.AddWithValue("#title", titlename);
command.Parameters.AddWithValue("#description", descname);
command.Parameters.AddWithValue("#quantity", "1");
MySqlDataReader result = command.ExecuteReader();
I'm just not sure how to word it to do the check.
UPDATE! Here is the working code.
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand updatecommand = connection.CreateCommand();
updatecommand.CommandText = "UPDATE tableName Set quantity = quantity +1 " +
"WHERE upc = #upc";
updatecommand.Parameters.AddWithValue("#upc", upc.Text);
using (MySqlDataReader updateResult = updatecommand.ExecuteReader())
{
if (updateResult.RecordsAffected == 0)
{
affected = true;
}
else
{
affected = false;
}
}
if(affected == true)
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(#upc, #title, #description, #quantity)";
command.Parameters.AddWithValue("#upc", upc.Text);
command.Parameters.AddWithValue("#title", titlename);//adding parameters SAFELY to the statement
command.Parameters.AddWithValue("#description", descname);
command.Parameters.AddWithValue("#quantity", "1");
MySqlDataReader result = command.ExecuteReader();
}
Although I've not worked specifically with MySqlDataReader, I would slightly change the queries around... the otherwise format (parameterization) you have for the insert is completely fine.
Although the ON DUPLICATE KEY UPDATE provided by Hristo is cool, you would be missing the other column elements for your record. I would change to..
MySqlCommand command = connection.CreateCommand();
command.CommandText = "UPDATE tableName Set Quantity = Quantity +1 " +
"WHERE upc = #upc"
command.Parameters.AddWithValue("#upc", upc.Text);
** Dont know how the value / status will be returned from the MySqlDataReader, but
result = command.ExecuteReader();
if( the status indicates it actually succeeded in an update,
or how many records were updated > 0 )
return; // you've just increased the counter...
OTHERWISE, it was not on file.. continue with the rest of your SQL-insert command, we can overwrite the last command instance...
command = connection.CreateCommand();
command.CommandText = "INSERT INTO tableName " +
"(upc, title, description, quantity) " +
"VALUES " +
"(#upc, #title, #description, #quantity)";
command.Parameters.AddWithValue("#upc", upc.Text);
command.Parameters.AddWithValue("#title", titlename);
command.Parameters.AddWithValue("#description", descname);
command.Parameters.AddWithValue("#quantity", "1");
result = command.ExecuteReader();
If UPC is you primary key you can use INSERT ON DUPLICATE KEY UPDATE functionality of MySQL database. If you dont want to INSERT the new UPC just run an UPDATE query if there is no such row if wont affect the data in the table.
UPDATE <tablename> SET quantity=quantity+1 WHERE UPC='<upc>'