//update, insert and delete data in database using stored procedure public int updateSP(String spName, Data data) { cmd = null; int result = 0; try { tran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = spName; cmd.Connection = conn; cmd.Transaction = tran; String key = null; SqlDbType sType = SqlDbType.NVarChar; int size = -1; Object[] keys = data.getKeys(); Object value = null; int length = keys.Length; //add parameters using keys if (keys != null) { for (int i = 0; i < length; i++) { key = "@" + keys[i].ToString(); value = data.get(keys[i]); size = data.getSize(key); sType = data.getType(key); if (size > 0) { cmd.Parameters.Add(key, sType); } else { cmd.Parameters.Add(key, sType, size); } cmd.Parameters[key].Value = value; } } result = cmd.ExecuteNonQuery(); tran.Commit(); } catch (Exception e) { Console.WriteLine(e.Message); //Trace. (e.Message); tran.Rollback(); } finally { if (cmd != null) { cmd.Parameters.Clear(); } } return result; }
//select data from database using stored procedure public Data selectSP(String spName, Data data) { cmd = null; Data result = new Data(); try { cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = spName; cmd.Connection = conn; String key = null; SqlDbType sType = SqlDbType.NVarChar; int size = -1; Object[] keys = data.getKeys(); Object value = null; int now = 0; //add parameters using keys if (keys != null) { int length = keys.Length; for (int i = 0; i < length; i++) { key = "@" + keys[i].ToString(); value = data.get(keys[i]); size = data.getSize(key); sType = data.getType(key); if (size > 0) { cmd.Parameters.Add(key, sType); } else { cmd.Parameters.Add(key, sType, size); } cmd.Parameters[key].Value = value; } } // get query results rdr = cmd.ExecuteReader(); //save result into Data while (rdr.Read()) { int fCount = rdr.FieldCount; for (int i = 0; i < fCount; i++) { result.add(now, rdr.GetName(i), rdr.GetValue(i)); } ++now; } } catch (Exception e) { Console.WriteLine(e.Message); result.ErrorMessage = e.Message; } finally { if (cmd != null) { cmd.Parameters.Clear(); } // close the reader if (rdr != null) { rdr.Close(); } } return result; }