Hi,
I created a web service which is called from the client side to store the data into the database. These data are sent every 200 ms from a single user and each time the data are sent the database connection is opened and closed which I believe is not good for performance.
The data are stored by calling REST.StoreAcceleration() method and SQLWorks.StoreAcceleration() the following way:
public Response StoreAcceleration(string strSessionString, string strMeasurementTime, string strAccelerationX, string strAccelerationY, string strAccelerationZ)
{
SQLWorks sqlWorks = new SQLWorks();
Response response = new Response();
try
{
string strTime = strMeasurementTime.Replace("_", " ");
DateTime measurementTime = DateTime.ParseExact(strTime, "yyyy-MM-dd HH:mm:ss:fff", null);
double accelerationX = Convert.ToDouble(strAccelerationX.Replace(".", ","));
double accelerationY = Convert.ToDouble(strAccelerationY.Replace(".", ","));
double accelerationZ = Convert.ToDouble(strAccelerationZ.Replace(".", ","));
sqlWorks.StoreAcceleration(strSessionString, measurementTime, accelerationX, accelerationY, accelerationZ);
response.Successful = true;
response.Comment = "Stored!";
}
catch(Exception ex)
{
string sDummy = ex.ToString();
response.Comment = "an error occured!";
response.Successful = false;
}
return response;
}
public bool StoreAcceleration(string strStringSession, DateTime receivedTime, double accelerationX, double accelerationY, double accelerationZ)
{
bool result = false;
string select =
"INSERT INTO acceleration (session_id, measurement_time, acceleration_x, acceleration_y, acceleration_z) VALUES (@sessionID, @measurementTime, @accelerationX, @accelerationY, @accelerationZ)";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(select, conn);
int sessionID = getSessionID(strStringSession);
if(sessionID == 0)
return false;
updateSessions(sessionID);
string strRecordTime = receivedTime.ToString("yyyy-MM-dd HH:mm:ss:fff");
cmd.Parameters.AddWithValue("sessionID", sessionID.ToString());
cmd.Parameters.AddWithValue("measurementTime", strRecordTime);
cmd.Parameters.AddWithValue("accelerationX", accelerationX.ToString());
cmd.Parameters.AddWithValue("accelerationY", accelerationY.ToString());
cmd.Parameters.AddWithValue("accelerationZ", accelerationZ.ToString());
try
{
conn.Open();
cmd.ExecuteNonQuery();
result = true;
}
catch(Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
return result;
}
The problem here is that SqlConnection is opened and closed on every method call.
I would appreciate if anyone could suggest how to improve the solution in order to prevent frequent database connection opening/closing.
Thanks!