Duplicate entry of same record in database - asp.net
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.
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();`
Asp.net , to_date Function
I want to update record in oracle db. But it gives me error "date format picture ends before converting..." I uses to_date function. datatype of column is DATE. Here is my query var updateddate = DateTime.Now; var testing= this.hidvalue.Value; var idrow = id.Text; var anserrow = lblanswer.Text; var weightpwd = lblweighted.Text; var solvetimerow =lblsolvetime.Text; var updatedby = Session["Name"]; string queryDuppass = "Update ADU.QAT_DATA set Question='" + idrow + "',Answer='" + anserrow + "', Question_Weighted='" + weightpwd + "', Resolve_Estimated_Time='" + solvetimerow + "', Updated_By='" + updatedby + "', Updated_Date= to_date('" + updateddate + "','mm-dd-yyyy hh12:mi:ss'" + ")" + " where ID='" + testing + "'";
Forward Slash is removed in path
I have set the html from code behind in ItemDataBound event of repeater but in html path is not right. Dim video_path = imgUrl + VideoPath + VideoName.split(".")(0) + ".mp4" Dim poster_path = imgUrl + VideoPath + VideoName.split(".")(0) + ".png" Dim DvVidContent As HtmlContainerControl = CType(e.Item.FindControl("DvVidContent"), HtmlContainerControl) Dim onclick = "'ShowVideoDialog('size_vp_" + count.ToString() + "', '" + video_path.ToString().Trim() + "');'" Dim Header As String = "<div style='position:relative;' Sequence='" + count.ToString() + "' id='" + ID.ToString() + "' class='SessionFolderViewChild'><img onerror='handleError(this);' src='" + poster_path.ToString() + "' alt='Thumbnail'/><img class='dv_play_icon' onclick='" + onclick + "' id='PlayVideo' style='position:absolute;top:8px;left:26px;height:100px;width:100px;' src='../../Images/icn_Play.png'/></a></div>" DvVidContent.InnerHtml = Header.Trim() count = count + After Html rendering its remove the forward slash and look like onclick="ShowVideoDialog("size_vp_1','.. .. resources sbs attachments steps351 step565 130906720751358852.mp4');
System.Data.SqlClient.SqlException: Incorrect syntax near ''
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.
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; } }