So I have a Database that I created a Dataset from, I'm attempting to run an Update on it and I cannot get it to update the Dataset (and subsequently the Database) with the result. I built the Query using Visual Studio's query builder and when I run it through there it changes the data in the way that it should. When I run the code I put in a MessageBox to show the number of rows the query changed and it is returning 1 as it should. I'm at a loss as to why it won't 'commit' the update and I'm sure I'm missing something very simple.
Here is the Query I setup (named "UpdateQuery")
UPDATE Bug_Master
SET Name = #Name, Test_App = #Test_App, Bug_Type = #Bug_Type, Bug_Active = #Bug_Active, Bug_Description = #Bug_Description, Bug_Keywords = #Bug_Keywords
WHERE (Id = #Original_Id);
In the Load event for the form I have
this.bug_MasterTableAdapter.Fill(this.bugManagerDataSet.Bug_Master);
And here is where I am calling the Query and trying to update (I know I should use 'using' but I'll pretty up the code after I get this to work so forgive the inelegance)
SqlConnection connection = new SqlConnection(strSQLConnectionString);
connection.Open();
int iResult = bug_MasterTableAdapter.UpdateQuery("Error One 1", "PassVault", "Runtime", "True", "Description Test", "Keywords Test", 1);
MessageBox.Show(iResult.ToString());
bug_MasterTableAdapter.Update(bugManagerDataSet.Bug_Master);
connection.Close();
As I mentioned above the MessageBox shows '1'. Is there a critical step I'm missing on how to do this? It has been a long time since I messed with SQL so I've had to bumble my way back to it and have no doubt I've missed/messed up some things.
Thanks in advance.
erik
Found the solution. Turns out the 'copy to output directory' property on the database file was set to 'always copy'. So when I ran the program it would make changes to the database in the \bin\debug folder while I was looking at the one in the app folder. Then when I would restart the program to check the values in there it would overwrite the changed version of the database in \bin\debug with the unchanged version from the project.
So, the upshot is for anyone else that runs into something similar is set the 'Copy to Output Directory' option on the database to 'Copy if Newer'.
Thanks to all who took a look.
erik
Related
So I am having a very weird issue, At first my code to insert items into my access database stopped working, it is a simple code like this:
using (OleDbConnection myCon = new OleDbConnection())
{
OleDbCommand cmd = new OleDbCommand()
{
CommandType = CommandType.Text,
CommandText = "insert into applicationSalts ([appName],[salt]) values (?,?)"
};
cmd.Parameters.AddWithValue("#appName", appName);
cmd.Parameters.AddWithValue("#salt", salt);
myCon.ConnectionString = publicDbConnectionString;
cmd.Connection = myCon;
myCon.Open();
int result = cmd.ExecuteNonQuery();
myCon.Close();
}
So it is very straight forward, inserting those values and I checked that result = 1 (query finished successfully).
Now it gets a bit weird, The database happens to not show any new values. Which is weird, Then I tried renaming the database and then all those records appear later! I tried using the database from another location (I was using it from C:/databaseName then now used it from D:/databaseName) then it worked. I moved the database file that worked back into C, then suddenly the records that appeared before disappeared.
Much weirder is that at the beginning one of the tables in the same database used to be working with an ideantical call as the one prior to this. But this one didnt! Then when I was trying to find the issue that one also stopped working..
Also after I manually changed some records when it was working through ms access it later ignored the changes..
I am slowly going insane as I am not really understanding what is going on, This is using access 2000 file format.
Edit: After further experimentation it is still getting weirder for me, While the file is called onlineDb.mdb it had a single record, deleting that made it disappear, Now renaming it to onDb.mdb made that record come back, adding other records that were missing. Then renaming to onlineDB.mdb again made all records disappear.
I have seen the other posts on this subject. Yet so far there has been no solution. I am working with Visual Studio 2013 in C#.
I have a database "Database1.mdf" with one table called Customers, which just has two records. I created the DataSet named CustomersDataSet (Menu: Project, Add New Data Source...) based upon this database.
This is my code.
CustomersDataSetTableAdapters.CustomersTableAdapter cta = new CustomersDataSetTableAdapters.CustomersTableAdapter();
CustomersDataSet ds = new CustomersDataSet();
// Fill our customersDataSetTable with the data from customers adapter
cta.Fill(ds.Customers);
Console.WriteLine("BEFORE");
foreach (CustomersDataSet.CustomersRow customer in ds.Customers.Rows)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
Console.WriteLine("\nMaking changes now...");
// Insert a new record
CustomersDataSet.CustomersRow newCustomer = ds.Customers.NewCustomersRow();
newCustomer.FirstName = "Brian";
newCustomer.LastName = "Faley";
newCustomer.City = "Denver";
newCustomer.State = "CO";
ds.Customers.AddCustomersRow(newCustomer);
// Update a record, [0] = gets access to the first row of the customers table
ds.Customers[0].FirstName = "Robert";
// Delete a record
ds.Customers[1].Delete();
// Update the dataset ds. Commit changes to the database
cta.Update(ds);
Console.WriteLine("\nAFTER");
foreach (CustomersDataSet.CustomersRow customer in ds.Customers.Rows)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
It works insofar as I do see the changes made to the dataset after "AFTER".
Yet I can run it as often as I wish - never are the changes written to the underlying database. The Update should do just that, but it does not. There is no AcceptChanges() in my code. I have followed up on all these suggestions - they do not lead anywhere.
Would someone have an idea?
I googled far and wide and all posts on this issue are unsolved.
When you debug the application the mdf file is copied to the bin\debug folder and your changes are committed to the database there.
Every time you start the project the mdf in the debug folder gets overwritten with the original database.
You can stop this behavior by going to the database settings in your solution and set the database to copy only if your version is newer.
Chances are your code was working all along.
Hope this helps.
I have a C# .NET WinForms application that uses Crystal Reports.
Crystal reports run fine on both x32 and x64 systems with the exception of reports containing subreports. Any report containing a subreport fails with the wonderful: "Log on failed" at ...VerifyDatabase() but only on x64 systems.
I have seen and fixed this problem in the past by unchecking Verify Database on every print, making sure the no data is being saved with the report and ensuring the correct driver and connection methods are being used in the designer. This problem is not going away and seems to only be affecting reports with subreports.
All projects in the solution are set to build to x32.
The x64 systems have the CR 32bit runtime installed.
The SQL Native Client is also installed.
I have tried many different combinations of report preparations steps like not verifying the database, not refreshing the report, verifying and not refreshing, refreshing and not verifying... it goes on and on.
Here is the current preparation method being used:
private T GetReport<T>() where T: ReportDocument, new()
{
var report = new T();
var connectionStringBuilder
= new SqlConnectionStringBuilder(this.ConnectionString);
var connectionInfo = new ConnectionInfo
{
DatabaseName = connectionStringBuilder.InitialCatalog,
UserID = connectionStringBuilder.UserID,
Password = connectionStringBuilder.Password,
ServerName = connectionStringBuilder.DataSource
};
Action<ReportDocument, bool, bool> setConnection = (document, verify, refresh) =>
{
document.DataSourceConnections.Clear();
document.DataSourceConnections[0].SetConnection(
connectionStringBuilder.DataSource,
connectionStringBuilder.InitialCatalog,
connectionStringBuilder.UserID,
connectionStringBuilder.Password
);
document.DataSourceConnections[0].IntegratedSecurity = false;
/*
foreach (Table table in document.Database.Tables)
{
var tableLogOnInfo = table.LogOnInfo;
tableLogOnInfo.ConnectionInfo = connectionInfo;
table.ApplyLogOnInfo(tableLogOnInfo);
}
* */
//document.SetDatabaseLogon(connectionInfo.UserID, connectionInfo.Password, connectionInfo.ServerName, connectionInfo.DatabaseName);
if (verify)
document.VerifyDatabase();
if (refresh)
document.Refresh();
};
for (var index = 0; index < report.Subreports.Count; index++)
{
var subreportName = report.Subreports[index].Name;
var subreport = report.OpenSubreport(subreportName);
setConnection(subreport, false, false);
}
setConnection(report, true, true);
return report;
}
SOLVED: I have gotten the report to work. I am not sure what part of this solution actually solved the problem but these are the steps I took.
I checked the data source per aMazing's suggestion below. (It was already OLE DB)
I removed all referenced to Crystal Reports in all projects in the solution.
I re-added the Crystal Reports references and made sure all the references were the same version and made sure all references were set to 'Specific Version' = True.
I set 'Copy Local' to True on the CR references on one project in the solution.
I changed the call to the **setConnection** to not verify.
I un-commented foreach table.ApplyLogOnInfo(tableLogOnInfo) section.
I'm not sure why it works now but it does. The table.ApplyLogOnInfo was un-commented in many of the permutations I tried earlier. Maybe I never hit this specific combination... but I don't care at this point.
SOLVED: I have gotten the report to work. I am not sure what part of this solution actually solved the problem but these are the steps I took.
I checked the data source per aMazing's suggestion below. (It was already OLE DB)
I removed all referenced to Crystal Reports in all projects in the solution.
I re-added the Crystal Reports references and made sure all the references were the same version and made sure all references were set to 'Specific Version' = True.
I set 'Copy Local' to True on the CR references on one project in the solution.
I changed the call to the **setConnection** to not verify.
I un-commented foreach table.ApplyLogOnInfo(tableLogOnInfo) section.
I'm not sure why it works now but it does. The table.ApplyLogOnInfo was un-commented in many of the permutations I tried earlier. Maybe I never hit this specific combination... but I don't care at this point.
Because I couldnt add a comment, this was the only way I could reply.
What SQL server are you using? I had something similar before.
Check the following on both report and sub report:
1) Right Click Datasource Properties
2) Select Set Datasource Location
3) On the connetion that the report is using, click expand Properties
4) Confirm that the Database Type = OLE DB (ADO) and Provider is SQLOLEDB.
That fixed my problem. I had set it to SQLNative Client before which was failing.
Hope it helps.
Thanks
Check if you have an Access database or any other 32 bit datasource in any of the subreports.
I had this same problem recently. I found the cause to be not setting the datasource, which in my case was due to an incorrect if statement, meaning the following line was not running:
repdoc.Subreports["SubReportName.rpt"].SetDataSource((DataTable)MyDataTable);
Hope this is of use.
I am using Visual Studio 2012. I have a very simple Products table in a Local Database (cleverly named Database1). It has two fields: id and Name. I preloaded it with a few test data.
The following code should update the Name of the first Product. Internally, it does. I can retrieve all Products and see that the first one's Name is "Shirt." But the change is never flushed to the database. The record is never updated. Examining the database reveals that the name has not been changed.
My question is simple: Why are changes not being sent to the database?
using (var context = new Database1Entities())
{
var products = context.Products;
products.First().Name = "Shirt";
context.SaveChanges();
}
Thanks in advance.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
EDIT:
I tried my best to enter the full code and output here. But, no matter what I do, I continue to get the "Your post appears to contain code that is not properly formatted" error message. After 30 minutes I am giving up.
EDIT:
The code and output is here: http://pastebin.com/GmQtwAND
I discovered the issue...and its solution.
The "Copy to Output Directory" property of the database file was set to "Copy always." This, of course, meant that every time the application was built, a fresh copy was placed into the Bin directory. The fix was to set it to "Copy if newer." Doh.
In other words, the changes were being persisted in the database, but then the database was being clobbered when the application got rebuilt.
Well this could mean that you're not tracking changes, how about you try to set the State to -> Modified and see if it's going to work:
var product = products.First();
product.Name = "Shirt";
product.State = EntityState.Modified;
context.SaveChanges();
If you want to enable it for the context you can do it like this:
context.Configuration.AutoDetectChangesEnabled = true;
I am having trouble updating an SQL database, the problem is not that it doesn't update at all, but that particular parameters are being updated while the others are not.
here is the code for updating the parameters:
string EditRequest = "UPDATE Requests SET Description = #Desc, BJustif = #Justif, Priority = #Priority, Requested_System = #Requested, Request_Status = #Stat WHERE";
EditRequest += " Req_ID=#ID";
SqlConnection Submit_conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DBConn"].ConnectionString);
SqlCommand Submit_comm = new SqlCommand(EditRequest, Submit_conn);
Submit_comm.Parameters.AddWithValue("#ID", Request.QueryString["reqid"]);
Submit_comm.Parameters.AddWithValue("#Desc", DescBox.Text);
Submit_comm.Parameters.AddWithValue("#Justif", JustifBox.Text);
Submit_comm.Parameters.AddWithValue("#Priority", PriorityList.SelectedValue);
Submit_comm.Parameters.AddWithValue("#Requested", RelatedBox.Text);
Submit_comm.Parameters.AddWithValue("#Stat", 1);
Submit_conn.Open();
Submit_comm.ExecuteNonQuery();
Submit_comm.Dispose();
Submit_comm = null;
Submit_conn.Close();
get_Description();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Refresh", "ReloadPage();", true);
this function is called by a button on a pop-up form which shows the parameters content that is being changed in a text box which is also used to submit the changes back to the database, but when I press submit, the parameters which are displayed on the form don't change, I can't find any problem wit the code, even though I've compared it to similar code which is working fine.
In case you need to, here is one of the text boxes I'm using to display and edit the content:
<asp:TextBox ID="JustifBox" TextMode="MultiLine" runat="server" Width="250" Height="50"></asp:TextBox>
What exactly is wrong with the code?
EDIT: I forgot to mention that when I traced the function, it appeared that the controls' content did not change when I submitted them, but were resubmitted as if they were unchanged in their original form.
You mentioned two problems here:
1) Fields in the database are not updated when the UPDATE is performed
2) The UI is not updated with the latest data
First tackle the SQL UPDATE query. What fields are not being updated? Copy paste the T-SQL query in the query analyzer and then check which field is being updated and which is NOT. Also, your code is OPEN to SQL injections so read about that and then adjust the code.
For the UI not being updated you need to see whether you are even populating the UI fields with the correct object.