The following is some info that I received from an earlier post!(Mikes.Nett) Can someone help me to revise this code so that I can connect to my database. I am limited in my understanding of how to make this savePersonell method interact with the information
that I am trying to access! The use of ids is something that I am not familair with so I need help to build my base of knowledge on this subject. Should I be intializing save personell data with numbers to index the ids, and if so can you explain how this
should be done??? Thanks, Markus33
(Mikes.Nett) Your data layer has some basic mistakes. You should be using parameters instead of concatenating variables directly into a SQL statement. Also,
you should use @@Identity to get the most recently created record - not MAX(Id). Also, why are you inserting a record and then updating it? You can
do the whole thing with one insert.
Here's a revised version that uses parameters and also takes an additional argument - a nullable int representing the ID of the record to be "saved". If you are updating an existing record, you pass a value in for hte int and the UPDATE statement is executed.
If you are creating a new record, you pass null in and the INSERT statement is executed instead. Mikes.net
publicstaticboolSavePersonnel(stringDatabase,stringFirstName,stringLastName,stringPayRate,stringStartDate,stringEndDate,int?Id){try{using(OleDbConnection conn =newOleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source="+Database)){
conn.Open();OleDbCommand command = conn.CreateCommand();
command.Parameters.AddWithValue("FirstName",FirstName);
command.Parameters.AddWithValue("LastName",LastName);
command.Parameters.AddWithValue("PayRate",PayRate);
command.Parameters.AddWithValue("StartDate",StartDate);
command.Parameters.AddWithValue("EndDate",EndDate);string strSQL;if(!Id.HasValue)// inserting a new record{
strSQL ="Insert into tblPersonnel (FirstName, LastName, PayRate, StartDate, EndDate) values (?,?,?,?,?)";}else// updating existing record{
strSQL ="Update tblPersonnel Set FirstName = ?, LastName = ?, PayRate = ?, StartDate = ?, EndDate = ? Where ID = ?";
command.Parameters.AddWithValue("ID", ID);}
command.CommandText= strSQL;
command.ExecuteNonQuery();returntrue;}}catch(Exception ex){returnfalse;}}