VB.NET TableAdapter insert query not saving to database - vb.net

I created an INSERT query to my UsersDataSet. (right-click -> new query -> sql -> insert). After calling UsersTableAdapter.InsertUser(user,pass,firstname,lastname), I notice the query executes successfully but the data is not saved to the database. Why is this happening?
PS: I have done this before and it do saves.

This is super stupid, the issue was that since I copied the MS Access file, everytime I rebuilt the project, the database file was also overwritten, along with the previous build files, with the blank database file I set as the datasource

You have to call TableAdapter.Update() to persist the changes back to the database. You are creating a row in the datatable, but not pushing your changes to the data source.
See http://msdn.microsoft.com/en-us/library/bz9tthwx.aspx

Related

How to resolve issue with DataSet and Database connection in Visual Studio?

I am using VB.NET with an MS Access database. There are two tables with a relationship with each other.
I followed the following to make a database connection with the dataset and binding Source.
Under Data Source add new Data Source
Database as a data source type
Dataset as a database model >>
Chosen Data connection
Under the database object, I selected Table (s) which want for the purpose like customer table also clicked on views
Then finish.
Now at Data source, selected Dataset then Table of Customers and drag details and data grid view to the form and add buttons for adding, deleting updating the records.
Now run the application.
After running the application, But it's not viewing, adding, updating, and deleting records from/to the database.
Code for adding a record to the database
CustomersBindingSource.AddNew()
Code for updating a record to the database
CustomersBindingSource.EndEdit()
CustomersTableAdapter.Update(SrsbdbDataSet.Customers)
Code for deleting a record from the database
CustomersBindingSource.RemoveCurrent()
I also edited a connection string from the app.config file to check the connection string issue but not useful for the issue.
Please let me know where I'm doing wrong.
CustomersBindingSource.AddNew()
This doesn't add a record to the access database, it adds a record to the BindingSource's list, which (when EndEdit is called on the BindingSource) is pushed into the YourDataSetName.Customers DataTable as a new DataRow - if you were to look at all the rows in YourDataSetName.Customers you'd see that there are some (downloaded from the db probably, when you started the app) and they have a DataRowState of Unchanged, and then there is the new one you added, with a DataRowState of Added
Nothing has been saved to the DB yet. This data is only in the dataset's datatable, which is a client side representation of a database table. It is not a database table in and of itself. It can certainly have more or fewer columns and of different types, than the database table. It's just temporary storage for database data; you download some, add some, change some, delete some, maybe save it etc. The relevant DataRow tracks all these things you do to its data and notes whether it is Added/Modified/Deleted/Unchanged etc
The TableAdapter is the thing that pushes the data back and forth between the DataTable and the database
You call CustomersTableAdapter.Update() when you want to save the data to the DB. Naming it Update was a crap idea on Microsoft's behalf, because it leads people to think it only performs SQL UPDATE queries; if it had been called SaveChanges (and later it was; EF uses SaveChanges) it would be more clear.. You just have to remember that one - "Update means Save"
So you call Update(datatable or dataset here) and pass in your DataTable with all its modified/deleted/added rows. The TableAdapter scans the whole DataTable row by row looking at the DataRowState of each row. If it's Added, then the TableAdapter will call its built in INSERT SQL query to save the row. If it's Modified, SQL UPDATE is performed. Deleted state causes an SQL DELETE. A datarow knows the original data that was downloaded and the data as it is now; this is sometimes vital in working out if someone else saved this row in the time we had it, so we can avoid overwriting their changes with ours
At the end of this process, the data has been saved, the rowstates have all been set from whatever they were, to Unchanged (because the data in the db is now the same, the row data no longer needs saving).
Think of that part of the process as being like the little * that appears on a text editor tab, when you edit the file - a datarow in state Added/Modified/Deleted has unsaved changes that need to be saved. After saving, the state goes back to Unchanged. Did I mention that TableAdapter.Update should have been called Save?
All in, the process for saving would be to ask the editing control to EndEdit() then ask the relevant bindingsource to EndEdit - this ensures we have a datatable with all changes committed and ready to save, and then call the tableadapter.Update. Probably the control the user was typing in will commit its edits when it loses focus, as the user clicks the save button.. But calling endedit makes sure. If you're uncertain, create a new form, drop a DataGridView on it out of the Data Sources window and take a look how the Save button is wired up - from memory it does a Validate, couple of EndEdits and a UpdateAll (TableAdapterManager, manages TableAdapters, calls Update on them in the right order to make sure that parent rows save before child rows)
If you started making more modifications, the row states would change again but just as before, the thing that commits the changes to the DB is TableAdapter.Update() regardless what kind of change you made
The final thing to watch out for here is that Access is a file based database. Probably you have your project in e.g.:
C:\projects\accesswhatever\
And you had your access db on e.g. your desktop:
c:\users\you\desktop\access.mdb
When you connected the access db into things, VS presented a long and wordy dialog (that no-one reads ;) ) where it basically says "i'll put the db in your project, and I'll make it copy out to the bin folder when you build".
So you click OK without considering the ramifications of it and you build. Your disk now looks like:
C:\users\you\desktop\access.mdb 'call it DB X
C:\projects\accesswhatever\access.mdb 'call it DB Y
C:\projects\accesswhatever\bin\debug\access.mdb 'call it DB Z
Your running program will save data in the last one, DB Z. Every time you build (which might happen every time you click play, if you make code changes), visual studio will delete Z and copy Y to Z.
You're now really confused; your code says it's saving. You're looking in either DB X on your desktop, or DB Y in your project base, and wondering where the heck is this data?
It's in DB Z, in the bin\debug folder, next to your app.exe - just remember that every time you build, VS wipes your changed database and replaces it with a clean one from way back when. If you want to change this, click the DB in solution explorer and set "Copy To Output" from "Copy Always" to "Copy If Newer". Now it'll only copy whenever you make a schema change, so.. Add a new table and then VS will wipe your nicely curated test db with a new one.. But it's more like OK because the new empty DB at least has that extra table that your program will crash without :)
An alternative is to add the new record directly in DataGridView and use new OleDbDataAdapter for the connection.
Remove 'CustomersBindingSource.AddNew()', and edit record in DataGridView:
Code in 'Update Record' button.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim connstring = "your connection string"
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter("select * from Customer", connstring)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
adapter.Update(CustomerDataSet.Customer)
End Sub

How can I copy MS SQL database data for a date range to be appended to DB on another computer?

I have a User Interface program written with VB.Net that collects instrumentation data from some PLC's and stores it in a MS SQL database. I need to be able to copy records from the DB based on a range of dates and save them in a file on a thumb drive. Then the file will need to be imported to a DB on another computer for analysis. I know SSMS can do a backup and restore but I don't think it can be based on a date range.
Simplest route I can think of would be (if the two DB are the same layout, table names etc) to download data, using a DataAdapter, into a DataTable and write it to disk with DataTable.WriteXml() then at the other end, DataTable.ReadXml() to get it from file back into a DataTable and write it into the destination DB with a DataAdapter. You'll need even fewer lines of code if you use strongly typed datatables (create a dataset)

How to introduce changes in pdm with sql script via PowerDesigner

~~~~~~~~~~~~~~~~
Hi, all!
I have a database model xxx.pdm and a sql script I want to apply to the db (so that generated xxx_db.sql, xxx_triggers.sql, etc will contain the changes - the files are used in whole application building process to generate yyy.db file).
I've tried to:
open the pdm file with PowerDesigner 16.5
go to Database->Update Model from Database...
select "using script files" and specified a sql file (with some create index, alter table statements). pressed ok
PowerDesigner showed progress dialog and a dialog merge models with yellow locks near some of the entities.
I try to generate database: Database->Generate database... in the dialog xxx_db.sql is selected.
the result - generation aborted due to errors detected during the verification of the model.
Category Check Object Location
Reference Incomplete join Reference 'FK_table1_col1' <Model>
Reference Incomplete join Reference 'FK_table2_col2' <Model>
at the same time the sql script is well executed via Sybase Interactive (cmd line).
Is my approach correct?
Maybe I'm doing something wrong?

Applying changes easily in Access Database

I have got a backup of a live database (A copy of an ACCDB format Access database) in which I've worked, added new fields to existing tables and whole new tables.
How do I get these changes and apply that fast in the running database?
In MS SQL Server, I'd right-click > Script Table As > Alter To, save the query and run it wherever I desire, is there an as easy way as that to do it in an Access Database ?
Details:
It's an ACCDB MS-Access database created on Access 2007, copied and edited in Access 2007, in which I need to get some "alter" scripts to run on the other database so that it has all the new columns and tables I've created on my copy.
For new tables, just import them from one database into the other. In the "External Data" section of the ribbon, choose the Access icon above "Import". That choice starts an import wizard to allow you to select which objects you want imported. You will have a choice to import just the table structure, or both structure and data.
Remou is right that you can use DDL ALTER TABLE statements to add new columns. However, DDL might not support every feature you want for your new columns. And if you want not just the empty columns added, but also also any data from those new columns, you will probably need to run UPDATE statements to get it into your new columns.
As far as "Script Table As", see if OmBelt's Export Table to SQL tool for MS Access can do what you want.
Edit: Allen Browne has sample ALTER TABLE statements. See CreateFieldDDL and the following one, CreateFieldDDL2.
You can run DDL in Access. I think it would be easiest to run the SQL with VBA, in this case.
There is a product called DbWeigher that can compare Access database schemas and synchronize them. You can get a free trial (30 days). DbWeigher will write a script of all schema differences and write it out as DDL. The script is thorough and includes relationships, indexes, validation rules, allow zero length, etc.
A free tool from the same developer, DBWConsole, will let you execute a DDL script against any Access database. If you wrote your own DDL scripts this would be an easy way to apply the changes to your live database. It even handles some DDL that I don't know how to process in VBA (so it must be magic). DBWConsole is included if you downloaded the trial version of DBWeigher. Be aware that you can't make schema changes to a table in a shared Access database if anyone has the table open.
DbWeigher creates a script of all differences between the two files. It can be a lot to manually parse through if you just want a few of the changes. I built a parser for DbWeigher script files so they could be filtered by table, to extract just the parts I wanted. I contacted the DbWeigher author about it but never heard back. It's safe to say that I have no affiliation with this developer.

Import from Excel to MySQL database using SQuirrel

I have an Excel spreadsheet with a few thousand entries in it. I want to import the table into a MySQL 4 database (that's what I'm given). I am using SQuirrel for GUI access to the database, which is being hosted remotely.
Is there a way to load the columns from the spreadsheet (which I can name according to the column names in the database table) to the database without copying the contents of a generated CSV file from that table? That is, can I run the LOAD command on a local file instructing it to load the contents into a remote database, and what are the possible performance implications of doing so?
Note, there is a auto-generated field in the table for assigning ids to new values, and I want to make sure that I don't override that id, since it is the primary key on the table (as well as other compound keys).
If you only have a few thousand entries in the spreadsheet then you shouldn't have performance problems (unless each row is very large of course).
You may have problems with some of the Excel data, e.g. currencies, best to try it and see what happens.
Re-reading your question, you will have to export the Excel into a text file which is stored locally. But there shouldn't be any problems loading a local file into a remote MySQL database. Not sure whether you can do this with Squirrel, you would need access to the MySQL command line to run the LOAD command.
The best way to do this would be to use Navicat if you have the budget to make a purchase?
I made this tool where you can paste in the contents of an Excel file and it generates the create table, and insert statements which you can then just run. (I'm assuming squirrel lets you run a SQL script?)
If you try it, let me know if it works for you.