ASP.NET SqlDataReader Incorrect syntax near - c#

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.

Related

C# ASP Web Form Logic

Could someone tell me what I'm doing wrong? I've tried to accomplish this in numerous different ways, but have not been able to. Without adding the parameters in, the form runs, but I need the parameters so that I can update records if it so evaluates. I may be off track, so any help is very appreciated.
For example, if a product code is entered and doesn't have a date already, the form should update the date with the current date/time. If the product code does have a date already, it should notify the user that the product has already shipped, else telling the user that the product is not in the database.
It evaluates by querying if there is a product code and if the date is null. If that evaluates to be true, then it should update that product code with a current timestamp in the date column. If that evaluates to be false, it checks to see if the product code exists in the table at all. If it does and the date column is not null, it reports that the product has already shipped, else, it reports that the product doesn't exist in the database.
Without the following parameters, it runs fine, providing the correct responses but, of course, it doesn't ever call to update a record.
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
With these parameters added in, I get an error stating the "The name 'command2' does not exist in the current context. But, I only get this error one. Sorry if my code is way out of line. Thanks in advance for your help!
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
{
protected void Page_Load(object sender, EventArgs e)
{
}
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);
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();
}
}
}
}
}
Put your parameters assignment inside a bracket and don't forget to call the execute method.
using (var command2 = new SqlCommand(sql2, connection))
{
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
command2.ExecuteNonQuery();
}
using (SqlCommand command2 = new SqlCommand(sql2, connection)) {
command2.Parameters.AddWithValue("#Value1", TextBox1.Text);
command2.Parameters.AddWithValue("#Value2", DateTime.Now);
}
Forgot your brackets.

Incorrect Syntax Error - c#

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.

Incorrect syntax near '(' when updating record in database

My code is producing an Incorrect syntax near '(' exception. I have tried two different ways but they both produce the same exception. I am trying to update a record in the database.
Here is my code and the line that produces the exception is the Execute non query line. The updater.Fill(dtable) which is commented out also produces the same exception.
protected void btnSave_Click(object sender, EventArgs e)
{
int found = 0; // No match found so far
// Get the current selected Manufacturer
string currentManufacturer = grdManufact.SelectedRow.Cells[1].Text;
string currentIsModerated = grdManufact.SelectedRow.Cells[3].Text;
// Connect to the database
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection conn = new SqlConnection(strConnectionString);
conn.Open();
// Try to find if new record would be a duplicate of an existing database record
if (txtManufactureName.Text != currentManufacturer)
{
string findrecord = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "'";
SqlDataAdapter adpt = new SqlDataAdapter(findrecord, conn);
DataTable dt = new DataTable();
found = adpt.Fill(dt);
}
if (found == 0) // New record is not a duplicate you can proceed with record update
{
String query;
if (checkBoxModerated.Checked)
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','true') WHERE ManufacturerName = " + currentManufacturer + ";";
}
else
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','false') WHERE ManufacturerName = " + currentManufacturer + ";";
}
using (SqlCommand command = new SqlCommand(query, conn))
{
command.ExecuteNonQuery();
}
//using (SqlDataAdapter updater = new SqlDataAdapter(command))
// {
// DataTable dtable = new DataTable();
// updater.Fill(dtable);
// }
txtMessage.Text = "Manufacturer record changed Successfully";
txtManufactureName.Text = "";
txtDescription.Text = "";
checkBoxModerated.Checked = false;
}
else
{ // Record is a duplicate of existing database records. Give error message.
txtMessage.Text = "Sorry, that manufacturer name already exists.";
}
}
You are using the incorrect syntax for UPDATE statements.
Instead of
UPDATE Table (Fields) VALUES (Values) WHERE ...
It should be
UPDATE Table SET Field1=Value1, Field2=Value2 WHERE ...
Additionally, you have a SQL injection vulnerability (although this is not the reason for your exception).
Do not use string concatenation for SQL queries with user input. Use prepared statements instead.
Try this approach , it's safer also:
var isModerated = checkBoxModerated.Checked ; //true or false
//var isModerated = (checkBoxModerated.Checked)? 'true' : 'false' ;
command.Text = "UPDATE VehicleManufacturer
SET ManufacturerName = #manufacturerName,
ManufacturerDescription = #manufacturerDescription,
IsModerated = #isModerated
WHERE ManufacturerName = #manufacturer_name";
command.Parameters.AddWithValue("#manufacturerName", txtManufactureName.Text);
command.Parameters.AddWithValue("#manufacturerDescription", txtDescription.Text);
command.Parameters.AddWithValue("#isModerated", isModerated);
command.Parameters.AddWithValue("#manufacturer_name", txtManufactureName.Text);
command.ExecuteNonQuery();

Info repeatedly getting recorded in DB

I have a Form where I am inserting a record into the database. There are two tables, table_1 is called members, and table_2 is called Amount.
I am using two SQL INSERT statements to send records to database , because that’s the way I have figured out -- there might be other ways, which I don’t know.
When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. Please assist.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CemiyetAidatSistem
{
public partial class AddMember : Form
{
public AddMember()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
MessageBox.Show("Data Added Scuessfully");
}
}
}
I have rewritten your code to correct errors and bad practices
string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (#id, #name, #address, #mobile, #email, #comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#comments", txtComments.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " +
"(#id, #year, #amount)";
cmd.Parameters.Clear();
cmd.CommandText = Sql; // <- missing this in the previous version.....
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtYear.Text);
cmd.Parameters.AddWithValue("#amount", txtAmount.Text);
cmd.ExecuteNonQuery();
}
}
What I have changed:
The second insert statement is wrong. Missing a comma between first
and second column
Removed the creation of the SqlConnection at the global level
Added appropriate using statement to dispose the SqlConnection and
SqlCommand also in case of exceptions
Used parameters for the two insert statements
Added square brackets around Year field (Year is a reserved keyword
in T-SQL)
Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. And the situation could be out of control in case of exceptions not correctly handled.
Now I have some doubt about your tables. The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection
I would also suggest changing your for loop to clear the controls replace this
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
with the following code using linq.
this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
keep in mind that 'this' will refer to the name of your Form
so it would be
(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());

Insert statement on asp.net not inserting on mysql table

I am creating a web form on asp.net that will allow the end user to assign multiple users bassed on a selected department to a quiz..
the database is mysql database since I use joomla
the tables on mysql are: jos_users_quizzes with the following columns:
id
quiz_id
user_id
I have a second is called called
jos_dhruprofile with this columns
id
name
username
department
I need to select all user ids from selected department and insert those id into the user_quizzes table.
I have two queries trying to to insert the first one which has the condition for selected department doesnt work while
the one without the were statement actually inserts, I get no errors , just the insertion doesnt go..
string quizidselected = DropDownList1.SelectedValue;
string deptselected = ListBox2.SelectedValue;
OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT uid, ' " + quizidselected + " ' FROM jos_dhruprofile WHERE department = ' " + deptselected.ToString() + " '");
// OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT uid, ' " + quizidselected + " ' FROM dhruprofile ");
THANKS IN ADVANCE FOR LOOKING MY CODE
Full code
Code from and ASP.NET form to insert ....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.Data.Odbc;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void InsertRecords(StringCollection sc)
{
string ConnectionString = #"driver={MySQL ODBC 5.1 Driver};server=appdevelsvr;database=xxxx;uid=xx;pwd=xx;";
OdbcConnection conn = new OdbcConnection(ConnectionString);
try
{
conn.Open();
string quizidselected = DropDownList1.SelectedValue;
string deptselected = ListBox2.SelectedValue;
OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT uid, ' " + quizidselected + " ' FROM jos_dhruprofile WHERE department = ' " + deptselected.ToString() + " '");
// OdbcCommand cmd = new OdbcCommand("INSERT INTO jos_jquarks_users_quizzes (user_id, quiz_id) SELECT uid, ' " + quizidselected + " ' FROM dhruprofile ");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
Response.Write(deptselected.ToString());
// Response.Write(sql.ToString());
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
foreach (ListItem item in ListBox2.Items)
{
if (item.Selected)
{
sc.Add(item.Text);
}
}
InsertRecords(sc);
}
}
I am assuming that the query you want us to debug is the one with the where clause.
Please set a breakpoint at the line where you are creating a new odbc command for cmd. You need to check the value of 'deptselected'.
Alternatively, you can debug.writeline the SQL statement and copy-paste it into a SQL query UI. Please run the select by itself. I think it will not return any rows because either 'deptselected' doesn't exist in your table or 'deptselected' is empty.
Also, two good programming pointers:-
1). Use parameterized SQL statements instead of appending values into the string. Your code is vulnerable to a SQL injection attack. This is very bad.
2). 'deptselected' is already a string, you do not need to 'ToString' it again.
Hope this helps.
Edit:-
I just read the comments above. Do a select * (star) on that table and where someother_column = another_value to get the same row that you are interested in. Check the string lenght of your department column. Check if you have spaces at the beginning of the string or after.

Categories