Saturday, 28 September 2013

C# and SQLCE Database Not Updating

C# and SQLCE Database Not Updating

Ok, I have been having a problem the last few days with my database not
updating. I can read the data fine and I'm not getting any exceptions
either. I'm trying to update the database then I try to read values again
after the update (during same run), and they still hold the original
values, so it doesn't seem to be an issue with the database being copied
to another folder (I'm using Copy if newer yet neither database is being
updated).
Here is the code I'm using. As you can see I tried a few different
approaches, none of which worked yet.
public void UpdateDatabaseInStock(string itemName, string tableName)
{
DataSet data = new DataSet("Items");
int val;
//get the file path to the database as a string
string dbfile =
new
System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName
+
"\\Database\\GameData.sdf";
//connect to the database
using (SqlCeConnection cntn = new SqlCeConnection("datasource=" +
dbfile))
{
//create an adapter to pull all data from the table
using (SqlCeDataAdapter adpt = new SqlCeDataAdapter
("SELECT * FROM " + tableName + " WHERE Name LIKE '%" +
itemName + "%'", cntn))
{
//put the data into a DataSet
adpt.Fill(data);
cntn.Close();
}
//fill the data from the Items table into a DataTable to return.
DataTable itemTable = data.Tables[0];
DataRow a = itemTable.Rows[0];
val = (short)a.ItemArray[3] - 1;
dbfile = "";
data.Dispose();
itemTable.Dispose();
SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = cntn;
cntn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE " + tableName + " SET [In Stock] =
@Value WHERE [Name] = '@ItemName'";
//cmd.Parameters.Add("@Value", SqlDbType.SmallInt);
//cmd.Parameters["@Value"].Value = val;
//cmd.Parameters.Add("@ItemName", SqlDbType.NChar, 75);
//cmd.Parameters["@ItemName"].Value = itemName;
cmd.Parameters.AddWithValue("@Value", val);
cmd.Parameters.AddWithValue("@ItemName", itemName);
cmd.ExecuteNonQuery();
//close the conenction
cntn.Close();
cmd.Dispose();
}
}
Any ideas to get it to actually update?

No comments:

Post a Comment