First off, I've only started working with databases and c# so I could be making a really stupid mistake here so apologies in advance. I'm connected to a SQL server express database and can read from it fine, however whenever I have updated my DataSet to add new columns and then try to update the data source it wont update successfully. Code below:
DataColumn newColumn;
SqlCommandBuilder cmdBuild = new SqlCommandBuilder(_myAdapt);
foreach (String s in myList)
{
newColumn = new DataColumn(s, System.Type.GetType("System.String"));
_myData.Tables["Table1"].Columns.Add(newColumn);
}
_myAdapt.Update(_myData, "Table1");
Anyone got any suggestions as to why this wont work? I've debugged it and the data set is definitely being updated with the new columns but I cant seem to update the data source.
Thanks for any responses.
Does that column exist in the database (and just not in your database), or are you trying to ALTER the table definition in the database using the dataset.
I don't believe the 2nd of the above is possible. Your dataset needs to have a column structure to match that of the database table that you're updating. You can however add as many rows as you like to the dataset and they will all INSERT to the database fine.
If you feel you have a need to add columns to your table at run-time I'd suggest revisiting your data-model. Where possible your column definitions should be be unchanging over time, to represent the main attributes of the data entities you're storing.
Related
I'm writing an C# application that watch for newly created xml files, and I want to insert some of the data in these XML files to a SQL database. One file is one row in the database.
What is the best and easiest way to do this?
What I have done so far is to defined a DataTable with the columns I want from the XML. After that I use ReadXML on the DataSet. This give me a DataSet with one table and one row, and the columns I want. So far it's perfect. But I can't find a good way to ONLY insert this new DataRow into my MSSQL database. I don't have any unique ID for that row yet. Would this make it easier? I don't want to map my dataset with the database, I'm only doing an insert...
You can do something like this to get the ID:
string query = "INSERT INTO Employees (EmployeeID, Name, Phone) "+
"OUTPUT INSERTED.EmployeeID "+
"VALUES (NEWID(), 'John Kris', '99-99999')";
Guid lastId = (Guid)command.ExecuteScalar();
The rest of the things you do sound ok for me.
I used LINQ to SQL to solve this. I set it up somewhat like described here:
LINQ to SQL.
On the data context I used InsertOnSubmit.
I have created one DataTable in C# dynamically. I want to insert this whole DataTable in MySql database table.
I am using MySql hence SqlBulkCopy is not an option for me.
I have tried MySqlBulkLoader but it seems it only insert data from file.
I can do it via iterating through every datarow of datatable and insert it to database.
Is there any another way I can achieve multiple inserts into database?
Thanks for any help!
If the number of rows are not much you can simply create an insert statement
INSERT INTO table VALUES (1,2,3), (4,5,6), (7,8,9);
Another article at http://www.codeproject.com/Articles/19727/ADO-NET-Generic-Copy-Table-Data-Function may help.
Though, if the number of rows are high, you can probably create a temporary text file and then use BulkLoader !
Hello I have a project that is linked to a SQL Compact database (xxx.sdf file) and need to properly transfer data from my datagridview and a table within it. This may not be how I should do it but I've spent hours trying to parametrize a whole bunch of queries to do this individually to the table (without success). I've been reading article after article and maybe I'm searching for the wrong thing.
My grid is bound to tableNameBindingSource. I cannot programmatically add rows to the grid because it is bound. I'm looking for the easiest way to add hundreds of rows to my SQL table at once and wanted to try to use the datagridview to accomplish that.
Can I (unbind the SQL table and) add the rows as needed to the datagridview table then force its contents to become the contents of the database table? Is there some kind of translator (I've used the SQLDataAdaptor to go from SQL table to datagridview)?
As long as your grid view table (source data) has the same structure (columns, data types) as your SQL table you should be able to use SQLBulkCopy to quickly copy the data.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
I've used this to copy 100,000s of rows in a relatively small amount of time.
Check out this CodeProject and the link above:
http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy
(edit) I just noticed you said SQLCompact. I'm not sure that SqlBulkCopy will work with the compact edition. There is a CodePlex project though called SQLCEBulkCopy.
You can just use a loop and then use a Insert query if that helps ...
SqlConnection cn = new SqlConnection(your connection parameters)
foreach (GridViewRow gvr in GridView1.Rows)
{
Label lblname = (Label)gvr.FindControl("lblname");
Label lbllogin = (Label)gvr.FindControl("lbllogin");
Label lblemail = (Label)gvr.FindControl("lblemail");
cn.open();
SqlCommand command = new SqlCommand("INSERT INTO Employee(Name,Login_Id,Email_Id) VALUES(#lblname,#lbllogin,#lblemail)", cn);
command.Parameters.AddWithValue("#lblname", lblname.Text.ToString());
command.Parameters.AddWithValue("#lbllogin", lbllogin.Text.ToString());
command.Parameters.AddWithValue("#lblemail", lblemail.Text.ToString());
command.ExecuteNonQuery();
cn.Close()
}
and put this code in a button click event(save button or something)
I have a DataGridView that displays data from a MS Access database. I'm using a DataSet with a TableAdapter and a BindingSource to link the data to the DataGridView:
tableAdapter = new AccountsTableAdapter();
dataTable = new Accounts.AccountsDataTable();
tableAdapter.Fill(dataTable);
tableBindingSource = new BindingSource();
tableBindingSource.DataSource = dataTable;
dataGridView1.DataSource = tableBindingSource;
I want to know how can I detect or get notified when the database table gets modified from outside my application - row updates, inserts, deletes performed on the database from the Access interface or from a different app.
Also, upon this presumed notification, how can I update my DataSet so that only the affected rows should be updated -> receive only the newly inserted rows, the affected field values of the modified ones and the indexes of the deleted.
So, basically, what I'm trying to obtain is a way of synchronizing my database table with the DataGridView. I've already managed to save to the database the rows that I modify or insert in the DataGridView, now it would be nice to be able to perform the reciprocal side of this database - view binding.
The only way I know of is to poll the database. If the data has a LastModified field, you can make requests to the database to get updated rows and then merge the results into your DataSet.
For example, let's say you populate the form from the sql "SELECT * FROM Contact". Then every minute or so, run the query "SELECT * FROM Contact WHERE LastModified > #LastFetched" where #LastFetched is the time you last got updates. You'll want to get the value for #LastFetched from the database since the client machine and database server might not have their times sync'ed close enough to work properly.
Then you just need to update the DataSet with the updates. If the form is bound properly, it should automatically be updated.
I have a strongly typed DataTable created with the VS2005/VS2008 DataSet designer.
The table has a Primary Key column that is a guid, which gets populated by SQL server. The problem is when I want add a row (or multiple rows) to my DataTable and then call the DataAdapter.Update method (passing in the DataTable). When DataAdapter.Update is called I get a SQL exception saying that I cannot insert NULL into the primary key column.
How do I tell the designer that this is an autogenerated column and I do not want to provide a value for new rows? I just want the value generated by SQL.
Am I missing something here, or is this a limitation of the DataSet designer?
I know how achieve this using LINQ to SQL, but unfortunatley I do not have it at my disposal for this project.
Possibly one of these:
If you don't need the column in your DataSet for your app, then remove it.
If you want the column but don't care to give it a value, then change it to allow DBNull.
You can always turn off constraint enforcement (probably a bad idea): DataSet.EnforceConstraints = false
You could fill the column with a surrogate key that does not get sent to the DB.
For the first two options, if you want the convenience of letting the designer keep your structure in sync with your database, then you could remove the column or allow null programmatically, perhaps right next to a "// HACK: " comment explaining why.
You're problably using DEFAULT NEWID() on your SQL Server table definition so the problem may be that the Dataset designer doesn't see this column as auto-generated.
Maybe generating guid in your application code could be a solution? If not, then you could set default value in you Dataset but then you're probably have to also change DataAdapter Insert/Update statements so that this default value doesn't get inserted into Sql Server table.
There could also be some other solution that I'm not aware of...