System.Data.SqlClient.SqlException: Incorrect syntax near '' - asp.net

cmd.Connection = con;
con.Open();
cmd.CommandText = "Update tiit.Enquiry Set Status='" + DropDownList4.SelectedValue + "', NextFollowup='" + TextBox8.Text + "', Remarks='" + TextBox9.Text + "', Name='" + TextBox1.Text + "', Email='" + TextBox2.Text + "', Phone='" + TextBox3.Text + "','','','','', City='" + TextBox4.Text + "', Country='" + TextBox5.Text + "', Course='" + TextBox6.Text + "', Comments='" + TextBox7.Text + "', Cost='" +TextBox14.Text+ "' where SN='" + HiddenField1.Value + "'";
int i = cmd.ExecuteNonQuery();
con.Close();

No, don't do this. Never use string concatenations (+ operator) when building your SQL queries. Use parametrized queries:
cmd.Connection = con;
con.Open();
cmd.CommandText = "UPDATE tiit.Enquiry Set Status=#Status, NextFollowup=#NextFollowup, ...";
cmd.Parameters.AddWithValue("#Status", DropDownList4.SelectedValue);
cmd.Parameters.AddWithValue("#NextFollowup", TextBox8.Text);
...
This way your code won't be vulnerable to SQL injection and you won't have any encoding problems.

In all probability this:
"Update tiit.Enquiry Set Status='"
is you problem. (I'm talking about the .)
I completely agree however - use parametrised queries.

Related

copy from html form and paste on outlook

I want to build an application in which when I fill up a form it will copy the data and on a button click it will paste some of the data in outlook email body
Thanks
I am about to finish my webform site
Issue : when I add small content (any type) to textarea and click on submit , it works !
But when i enter long multi line text in textarea it give me syntax error near s.
SqlConnection con = new SqlConnection("Data source=hidden; initial catalog=dsatdata; User id=sa; password=xxxxxx");
con.Open();
var query = "insert into escalationmatrix values ('" + lbl_case_number.Text + "','" + Request.Form["statust"].ToString() + "','" + Request.Form["status_summaryt"].ToString() + "', '" + Request.Form["impact_severityt"].ToString() + "', '" + Request.Form["next_stept"] + "', '" + Request.Form["root_causet"] + "','" + DateTime.Now + "')";
// SqlCommand cmd = new SqlCommand("UPDATE [escalation] SET [Status] = '" + Request.Form["statust"].ToString() + "', [status_summary] = '" + Request.Form["status_summaryt"].ToString() + "', [impact_severity] = '" + Request.Form["impact_severityt"].ToString() + "', [next_step] = '" + Request.Form["next_stept"] + "', [root_cause] = '" + Request.Form["root_causet"] + "' WHERE [Case_Number] = '" + lbl_case_number.Text + "'" , con);
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();`

Duplicate entry of same record in database

I have one form which takes lot of input data from users including image. Data inserts properly in table but it makes duplicate entry of same record in datatable. Please help I don't understand why it's taking duplicate entry of same data.
Private Sub save_Click(sender As Object, e As EventArgs) Handles save.Click
Dim name, businessCategory, subcategory, conPerson, website, email, phoneNo1, phoneNo2, mobileNumber, building, street, landpoint, area, city, stateName, zipCode, about, reg, foundationDate, founder, genBeds, icuBeds, mondayIn, mondayOut, tuesdayIn, tuesdayOut, wedIn, wedOut, thursdayIn, thursdayOut, fridayIn, fridayOut, saturdayIn, saturdayOut, sundayIn, sundayOut, visitIn, visitOut, fees, bestFor As String
name = businessName.Text
businessCategory = businessCat.Text
subcategory = subCat.SelectedItem.ToString
conPerson = contactPerson.Text
website = websiteName.Text
email = emailName.Text
phoneNo1 = phone1.Text
phoneNo2 = phone2.Text
mobileNumber = mobile.Text
building = buildingName.Text
street = address.Text
landpoint = landmark.Text
area = areaName.Text
city = suburb.Text
stateName = state.Text
zipCode = zip.Text
about = overview.Text
reg = regNo.Text
foundationDate = foundation.Text
founder = founderName.Text
genBeds = GeneralBeds.Text
icuBeds = ICU.Text
mondayIn = mondayFrom.SelectedItem.ToString
mondayOut = mondayTo.SelectedItem.ToString
tuesdayIn = tuesdayFrom.SelectedItem.ToString
tuesdayOut = tuesdayTo.SelectedItem.ToString
wedIn = wedFrom.SelectedItem.ToString
wedOut = wedTo.SelectedItem.ToString
thursdayIn = thursdayFrom.SelectedItem.ToString
thursdayOut = thursdayTo.SelectedItem.ToString
fridayIn = fridayFrom.SelectedItem.ToString
fridayOut = fridayTo.SelectedItem.ToString
saturdayIn = saturdayFrom.SelectedItem.ToString
saturdayOut = saturdayTo.SelectedItem.ToString
sundayIn = sundayFrom.SelectedItem.ToString
sundayOut = sundayTo.SelectedItem.ToString
visitIn = visitFrom.SelectedItem.ToString
visitOut = visitTo.SelectedItem.ToString
fees = consultinfees.Text
bestFor = bestknowFor.Text
Try
Dim filename As String = Path.GetFileName(profileDP.PostedFile.FileName)
profileDP.SaveAs(Server.MapPath("assets/images/hospitals/" + filename))
con.Open()
Dim str1 As String = "INSERT INTO hospitals (`name`, `category`, `subcategory`, `contactPerson`, `websiteName`, `email`, `phone1`, `phone2`, `mobileNumber`, `buildingName`, `streetName`, `landmark`, `areaName`, `city`, `State`, `zipCode`, `thumbnail`, `consultancyFees`, `overview`, `Founder`, `establishment`, `registration`, `generalBed`, `icuBed`, `mondayFrom`, `mondayTo`, `tuesdayFrom`, `tuesdayTo`, `wednesdayFrom`, `wednesdayTo`, `thursdayFrom`, `thursdayTo`, `fridayFrom`, `fridayTo`, `saturdayFrom`, `saturdayTo`, `sundayFrom`, `sundayTo`, `visitFrom`, `visitTo`, `bestKnownFor`, `status`) values ('" + name + "', '" + businessCategory + "', '" + subcategory + "', '" + conPerson + "', '" + website + "', '" + email + "', '" + phoneNo1 + "', '" + phoneNo2 + "', '" + mobileNumber + "', '" + building + "', '" + street + "', '" + landpoint + "', '" + area + "', '" + city + "', '" + stateName + "', '" + zipCode + "', 'list-business/assets/images/hospitals/" + filename + "', '" + fees + "', '" + about + "', '" + founder + "', '" + foundationDate + "', '" + reg + "', '" + genBeds + "', '" + icuBeds + "', '" + mondayIn + "', '" + mondayOut + "', '" + tuesdayIn + "', '" + tuesdayOut + "', '" + wedIn + "', '" + wedOut + "', '" + thursdayIn + "', '" + thursdayOut + "', '" + fridayIn + "', '" + fridayOut + "', '" + saturdayIn + "', '" + saturdayOut + "', '" + sundayIn + "', '" + sundayOut + "', '" + visitIn + "', '" + visitOut + "', '" + bestFor + "', 'active' )"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
command.Parameters.AddWithValue("#Content_Type", "assets/images/hospitals/" + filename)
command.ExecuteNonQuery()
str2 = command.ExecuteReader
con.Close()
Response.Write("Hospital added successfully!")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Please pick only one between command.ExecuteNonQuery() or str2 = command.ExecuteReader.
ExecuteReader used for getting the query results as a DataReader
object. It is readonly forward only retrieval of records and it uses
select command to read through the table from the first to the last.
ExecuteNonQuery used for executing queries that does not return any
data. It is used to execute the sql statements like update, insert,
delete etc. ExecuteNonQuery executes the command and returns the
number of rows affected. - from this site
I don't see why you should use ExecuteReader if you're just going to insert a record.
Cheers!
You should use only ExecuteNonQuery() and only once if you are using INSERT,UPDATE,DELETE statements.
ExecuteReader() is for retrieving records from database table.
You are doing both and thats why its inserting twice.

incorrect syntax near the keyword 'Values'

this is my code.i want to save these values into database.And an error occured,
incorrect syntax near the keyword Values
foreach (GridViewRow gvr in GridView1.Rows)
{
string strcon1;
strcon1 = ConfigurationManager.ConnectionStrings["fwma_devConnectionString"].ConnectionString;
SqlConnection con1 = new SqlConnection(strcon1);
con1.Open();
SqlCommand com3 = new SqlCommand(strcon);
TextBox tb = (TextBox)gvr.FindControl("TextBox2");//value
string txt = tb.Text;
Label propertylabel = (Label)gvr.FindControl("Label4");//id-property
com3.CommandText = "INSERT INTO BrandProperties(PropertyID,BrandID,Values) values(" + propertylabel.Text + "," + B_id.Text + "," + tb.Text + " ), con1";
com3.Connection = con1;
com3.ExecuteNonQuery();
con1.Close();
use this
com3.CommandText = "INSERT INTO BrandProperties(PropertyID,BrandID,Values) values('" + propertylabel.Text + "','" + B_id.Text + "','" + tb.Text + "')";
instead of
com3.CommandText = "INSERT INTO BrandProperties(PropertyID,BrandID,Values) values(" + propertylabel.Text + "," + B_id.Text + "," + tb.Text + " ), con1";
If you are using the reserved keywords ,you should specify delimited identifiers either quoted or bracketed.
example using bracketed
com3.CommandText = "INSERT INTO BrandProperties(PropertyID,BrandID,[Values]) values(" + propertylabel.Text + "," + B_id.Text + "," + tb.Text + " ), con1";
Shouldn't this line be like this?
com3.CommandText = "INSERT INTO BrandProperties(PropertyID,BrandID,Values) values(" + propertylabel.Text + "," + B_id.Text + "," + tb.Text + ")";
and please use command parameters:
When should "SqlDbType" and "size" be used when adding SqlCommand Parameters?

Website's performance issue

I have an Asp.Net website with one web page whose sole purpose is receiving data in the form of a query string then separate it as required and store this data to the database.
This data comes from several Vehicle Tracking Systems. Each vehicle sends a string of data as query string every 30 seconds.
I have written the code in my webpage in such a way that as the webpage is accessed, in the page load, I read the query string and do the insert operation into the database. Something like this-
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
string input = Request.QueryString["vinput"];
var m = Regex.Match(input, #"~(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#");
if (m.Success)
{
string[] vals = new string[20];
int j = 1;
for (int i = 0; i < 20; i++)
{
vals[i] = m.Groups[j].Value;
j++;
}
cmd.CommandText = "insert into tracking (vehicle_no,hardware_id,lat,lng,speed,direction,an0,an1,an2,an3,di0,di1,di2,di3,do0,do1,do2,do3,tdate,ttime) values('" + vals[0] + "','" + vals[1] + "','" + vals[2] + "','" + vals[3] + "','" + vals[4] + "','" + vals[5] + "','" + vals[6] + "','" + vals[7] + "','" + vals[8] + "','" + vals[9] + "','" + vals[10] + "','" + vals[11] + "','" + vals[12] + "','" + vals[13] + "','" + vals[14] + "','" + vals[15] + "','" + vals[16] + "','" + vals[17] + "','" + vals[18] + "','" + vals[19] + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
I created a simulator app for testing this site in place of vehicle tracking systems. This site works fine when there is data coming from one to three simulator instances, but fails to save data to database when more than 3 simulator instances send data simultaneously(Approximately).
For example, I am sending 5 records, each one at a time from the simulator and 6 such simulator instances sending data to the page. At the end in the database I see only 15 records inserted instead of 30 records. By the way this website runs in IIS 5.1.
How do I deal with this issue? Suggestions please.
UPDATE: Finally found the issue. After a lot of googling found this link and this. Its with the server, since the request limit is only 3 for basic/starter in windows xp IIS.
No point in using a Page when you can use something lighter weight like a handler. You can switch a few things around, but this is not a heavy operation. Here's a pretty optimal way to do it with one exception and that would be to make a stored procedure rather than generating an insert statement from a string:
public class htest : System.Web.IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(System.Web.HttpContext context)
{
System.Web.HttpRequest Request = context.Request;
Match m = Regex.Match(Request.QueryString["vinput"], #"~(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#(.+)#");
if (m.Success)
{
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection())
{
try
{
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("command", con);
string[] vals = new string[20];
int j = 1;
for (int i = 0; i < 20; i++)
{
vals[i] = m.Groups[j].Value;
j++;
}
cmd.CommandText = "insert into tracking (vehicle_no,hardware_id,lat,lng,speed,direction,an0,an1,an2,an3,di0,di1,di2,di3,do0,do1,do2,do3,tdate,ttime) values('" + vals[0] + "','" + vals[1] + "','" + vals[2] + "','" + vals[3] + "','" + vals[4] + "','" + vals[5] + "','" + vals[6] + "','" + vals[7] + "','" + vals[8] + "','" + vals[9] + "','" + vals[10] + "','" + vals[11] + "','" + vals[12] + "','" + vals[13] + "','" + vals[14] + "','" + vals[15] + "','" + vals[16] + "','" + vals[17] + "','" + vals[18] + "','" + vals[19] + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
catch
{
//At least do some type of logging in this event.
}
finally
{
con.Close();
}
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("Success");
}
}
Obviously you can use some boolean values to determine what you write back to the client at the end.
few suggestions..
You are opening connection. please close it at bottom as well. Dispose cmd object as well.
Put your INSERT Ststement into a SQL Transcation
USe try and Catch (USe the Catch clause to store error messages into Database , ex.message returns error detail.)

How to connect mysql to DevExpress ASPxScheduler without SqlDataSource

I have an ASP.net project I'm looking at and they want to use MySQL. I'm used to SQL server but using mySQL shouldn't be a problem.
Normally the control would like a SqlDataSource to bind to but that's not available with MySQL (from other posts on this site).
What's the best way to connect MySQL and the DevExpress ASPxScheduler so that you can create appointments?
Why not an ObjectDataSource and write the data layer? Or use LLBLGen, I think it works just fine with MySQL. The one caveat I've seen is that the MySQL ODBC and ADO drivers have issues with metadata.
I did end up using the objectdatasource and the ObjectCreated method and wrote the datalayer to insert records into the mysql database. I've included my code just incase someone needs some help with some of the logic.
protected void appointmentsDataSource_ObjectCreated(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = new CustomEventDataSource(GetCustomEvents());
}
public void InsertAppointment()
{
//need to reformat the dates
string tempStartDate;
string tempStartMinutes;
if (appointmentobject.Start.Minute.ToString().Length == 1)
{
tempStartMinutes = "0" + appointmentobject.Start.Minute.ToString();
}
else
{
tempStartMinutes = appointmentobject.Start.Minute.ToString();
}
tempStartDate = AppointmentObject.Start.Year + "-"
+ AppointmentObject.Start.Month + "-"
+ appointmentobject.Start.Day + " "
+ appointmentobject.Start.Hour + ":"
+ tempStartMinutes;
string tempEndDate;
string tempEndMinutes;
if (appointmentobject.End.Minute.ToString().Length == 1)
{
tempEndMinutes = "0" + appointmentobject.End.Minute.ToString();
}
else
{
tempEndMinutes = appointmentobject.End.Minute.ToString();
}
tempEndDate = AppointmentObject.End.Year + "-"
+ AppointmentObject.End.Month + "-"
+ appointmentobject.End.Day + " "
+ appointmentobject.End.Hour + ":"
+ tempEndMinutes;
//TODO Add CustomField : Need to add to this Insert Statement
//Change the appointment subject
string NewSubject = AppointmentObject.CustomFields["fldFirstName"]
+ ", " + AppointmentObject.CustomFields["fldLastName"]
+ ", " + AppointmentObject.CustomFields["fldClassID"]
+ ", " + AppointmentObject.CustomFields["fldPhoneNumberDay"];
string mySQLQueryString = #"INSERT INTO appointment (StartDate,EndDate,Subject,Status,Description,label,location,Type,FirstName,
LastName,PhoneNumberDay,PhoneNumberEvening,DriversLicenseNumber,Email,RentalCar,Payment,ConfirmationNumber,
PermitNumber,ClassID,CreateDate,CreateUser,NoticeToReport)
VALUES('" + tempStartDate + "','"
+ tempEndDate + "', '"
//+ AppointmentObject.Subject + "',"
+ NewSubject + "',"
+ AppointmentObject.StatusId + ",'"
+ AppointmentObject.Description + "',"
+ AppointmentObject.LabelId + ", '"
+ AppointmentObject.Location + "',"
+ "0, '" //type
+ AppointmentObject.CustomFields["fldFirstName"] + "','"
+ AppointmentObject.CustomFields["fldLastName"] + "','"
+ AppointmentObject.CustomFields["fldPhoneNumberDay"] + "','"
+ AppointmentObject.CustomFields["fldPhoneNumberEvening"] + "','"
+ AppointmentObject.CustomFields["fldDriversLicenseNumber"] + "','"
+ AppointmentObject.CustomFields["fldEmail"] + "',"
+ AppointmentObject.CustomFields["fldRentalCar"] + ","
+ AppointmentObject.CustomFields["fldPayment"] + ",'"
+ AppointmentObject.CustomFields["fldConfirmationNumber"] + "','"
+ AppointmentObject.CustomFields["fldPermitNumber"] + "',"
+ AppointmentObject.CustomFields["fldClassID"] + ", '"
//ignore create date for now.
//+ AppointmentObject.CustomFields["fldCreateDate"] + "', '"
+ "2009-01-01 12:00', '"
+ AppointmentObject.CustomFields["fldCreateUser"] + "', "
+ AppointmentObject.CustomFields["fldNoticeToReport"] + ")";
MySqlConnections test = new MySqlConnections();
test.InsertRow(mySQLQueryString);
}
public class MySqlConnections
{
private static string DriverConnectionString = "Database=driverexam;Data Source=localhost;User Id=ART;Password=art01";
public DataSet SelectRows(DataSet dataset, string query, string tablename)
{
MySqlConnection conn = new MySqlConnection(DriverConnectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand(query, conn);
adapter.Fill(dataset, tablename);
conn.Close();
return dataset;
}
public bool InsertRow(string query)
{
// MySqlConnection conn = new MySqlConnection(DriverConnectionString);
MySqlConnection conn = new MySqlConnection();
MySqlCommand cmd = new MySqlCommand();
conn.ConnectionString = DriverConnectionString;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
Console.WriteLine("Success Occurred ");
} //end of try
catch(Exception ex)
{
Console.WriteLine("Error Occurred - " + ex.Message);
}
return true;
}
}

Resources