Question
I wrote a program which includes writing and reading from database. When I run the app and try to perform writing I call the following method:
public static void AddMessage(string callID, string content)
{
string select =
"INSERT INTO Sporocilo (oznaka_klica, smer, vsebina, prebrano, cas_zapisa) VALUES (@callId, 0, @content, 0, @insertTime)";
SqlCommand cmd = new SqlCommand(select, conn);
cmd.Parameters.AddWithValue("callId", callID.ToString());
cmd.Parameters.AddWithValue("content", content);
cmd.Parameters.AddWithValue("insertTime", "10.10.2008");
try
{
conn.Open();
cmd.ExecuteScalar();
}
catch(Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
}
After the method call I read all the records from the table and display them in the form. The record inserted before refresh could be seen but then when I exit the app and look at the table I don't see the record.
Does anyone know what could cause such behavior?
Solution
Are you performing a commit after this? It might be running your statement but then not committing the changes and doing an implicit rollback.
I think the exception handling looks dodgy. There is no point catching something unless you can actually handle it in some way. The top level of your framework is the place for catching and reporting unexpected exceptions.
OTHER TIPS
Have you tried setting the return value of the ExecuteScalar method to an int and then checking value against the table?
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored
public static int AddMessage(string callID, string content)
{
Int32 newProdID = 0
string select =
"INSERT INTO Sporocilo (oznaka_klica, smer, vsebina, prebrano, cas_zapisa) VALUES (@callId, 0, @content, 0, @insertTime); SELECT CAST(scope_identity() AS int);";
SqlCommand cmd = new SqlCommand(select, conn);
cmd.Parameters.AddWithValue("callId", callID.ToString());
cmd.Parameters.AddWithValue("content", content);
cmd.Parameters.AddWithValue("insertTime", "10.10.2008");
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch(Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
return (int)newProdID
}
I found the problem. I modified the automatically generated connection string
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\URSZRDB.mdf;Integrated Security=True;User Instance=True"
with
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Niko\Documents\Visual Studio 2008\Projects\URSZRWAPChat\URSZRWAPChat\URSZRDB.mdf;Integrated Security=True;User Instance=True"
and now it works.
It's not the first time I write this kind of program and so far everything has gone well this way...