13.07.2015 Views

Software Engineering for Internet Applications - Student Community

Software Engineering for Internet Applications - Student Community

Software Engineering for Internet Applications - Student Community

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

create table km_object_views (object_view_id integer primary key,-- which useruser_idnot null references users,-- two columns to specify which objectobject_id integer not null,table_name varchar(21) not null,view_time timestamp(0) not null,reuse_pchar(1) default 'f'check(reuse_p in ('t','f')));Modify object-view-one so that it will insert a row into thekm_object_views table if and only if there isn't already a log row<strong>for</strong> this user/object pair within 24 hours. You can do this with thefollowing procedure:2801. open a transaction2. lock the table3. count the number of matching rows within the last 24 hours4. compare the result to 0 and insert if necessary5. close the transactionThis appears to be an awfully big hammer <strong>for</strong> a seemingly simpleproblem. Is it possible to do this in one statement?Let's start with Oracle. Here's an example of an INSERT statementthat only has an effect if there isn't already a row in the table:insert into km_object_views (object_view_id,user_id, object_id, table_name, view_time)select km_object_view_id.nextval, 227, 891,'algorithm', current_timestamp(0)from dualwhere 0 = (select count(*)from km_object_viewswhere user_id = 227and object_id = 891and view_time > current_timestamp -interval '1' day);The structure of this statement is "insert into KM_OBJECT_VIEWSthe result of querying the 1-row system table DUAL". We're notpulling any data from the DUAL table, only including constants in theSELECT list. Nor is the WHERE clause restricting results based onin<strong>for</strong>mation in the DUAL table; it is querying KM_OBJECT_VIEWS.{object objResult = null;string strResult = null;string strEmployeeID = "PMA42628M";//Initialize the database connection,// command and parameter objects.SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["connStr"]);SqlCommand cmd = new SqlCommand("select fname from employee where emp_id =@emp_id");SqlParameter param = newSqlParameter("@emp_id",strEmployeeID);//Associate the connection with the command.cmd.Connection = conn;//Bind the parameter value to the command.cmd.Parameters.Add(param);//Connect to the database and// run the command.try{conn.Open();objResult = cmd.ExecuteScalar();}catch (Exception e){Console.WriteLine("Database error: {0}",e.ToString());}finally{//Clean up.if(!conn.State.Equals(ConnectionState.Closed)){conn.Close();}}//Convert the query result to a string.if (objResult == null)69

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!