Copy from dataset to access table in C#? - c#

I have a dataset (from an XML file), I want to read the schema and values from this dataset and copy it into an access table.
I want to create the access database on fly (can use ADOX), create an access table (from ADOX) create the schema in this table and copy the values from dataset into this table.
I am getting an error when i try to create the table and add columns in it, Below is the code snippet which is giving me an error
DataSet ds = new DataSet();
Console.Write("The NAME IS" + FileName.Text.ToString());
ds.ReadXml("FILE_PATH" + FileName.Text.ToString());
ADOX.Catalog cat = new Catalog();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='DATABASE_NAME';Jet OLEDB:Engine Type=5");
Table tab = new Table();
tab.Columns.Append("Column Name", DataTypeEnum.adVarChar, 50);
// I am inserting 32 more columns in this manner
cat.Tables.Append(tab);
When I run this code block I get COM Exception : "TableID is invalid".
Am I trying to do this with a right approach? How can I copy the values from dataset to this table?

Could you try to assign a name to the table?
tab.TableName = "MyName";

Related

Table schema as DataTable?

I did a search and found some seemingly related answers, but they don't really do what I'm after.
Given a valid connection string and a table name, I want to get a DataTable of the table. I.e. if the table has a column called "Name", I want the DataTable set up so I can do dt["Name"] = "blah";
The trick is, I don't want to hard code any of that stuff, I want to do it dynamically.
People tell you to use SqlConnection.GetSchema, but that gives you back a table with a bunch of stuff in it.
Everybody has random tricks like TOP 0 * from the table and get the schema from there, etc.
But is there a way to get the table with the primary keys, unique indexes, etc. Ie.. in the final format to do a bulk insert.
You can use SqlDataAdapter.FillSchema:
var connection = #"Your connection string";
var command = "SELECT * FROM Table1";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(command, connection);
var dataTable = new DataTable();
dataAdapter.FillSchema(dataTable, SchemaType.Mapped);
This way you will have an empty DataTable with columns and keys defined and ready to use in code like dataTable["Name"] = "blah";.

DataTable with existing Schema not Importing DataRow of same Schema

Greets! I am having problems importing a row I created into a DataTable that resides in a DataSet. I pre-populate the "newDataSet" from a SQL Database that is empty but it does contain Tables with a Schema already set up. I have verified that the DataTables in "newDataSet" are getting the Schema imported to them.
Everything looks right as there is no error logs, but no datarow is ever added. Both my Console.WriteLine report back the same Count.
Thank you for taking the time to review this. I appreciate you.
Initial Setup:
var DataSet newDataSet = new DataSet("foo"); // A SQL Adapater was used to fill this from a pre existing Database.
var checkDataSet = new DataSet();
var checkDataTable = new DataTable();
Cloning the DataSet and DataTable.
checkDataSet = newDataSet.Clone();
checkDataTable = checkDataSet.Tables["moreFoo"].Clone();
Creating the DataRow:
var newDataRow = checkDataTable.NewRow();
Filling the Columns in the DataRow:
newDataRow[0] = obj1;
newDataRow[1] = obj2;
newDataRow[2] = obj3;
Importing the DataRow to the "newDataSet" DataTable:
Console.WriteLine(newDataSet.Tables["moreFoo"].Rows.Count.ToString());
newDataSet.Tables["moreFoo"].ImportRow(newDataRow);
Console.WritelLine(newDataSet.Tables["moreFoo"].Rows.Count.ToString());
The answer is:
newDataSet.Tables["moreFoo"].ImportRow(newDataRow);
should be:
newDataSet.Tables["moreFoo"].Rows.Add(newDataRow.ItemArray);

Updating SQL Server database with SqlDataAdapter

I have a DataTable with new entries, and I want to add these to an existing database.
So I create a SqlDataAdapter and fill a second table with it, then I merge the two tables, and update the database, but nothing happens, the return value is 0, the database stays the same.
Here's my code:
DBManager.DBDestinationConnect(textBox10.Text, textBox9.Text, textBox8.Text, textBox7.Text, ref destinationConnection);
//DBManager is a Class, to connect with the database
CategoryAdapterBackup = new SqlDataAdapter("SELECT*FROM " + tablename, destinationConnection);
CategoryTableBackup = new DataTable();
CategoryAdapterBackup.Fill(CategoryTableBackup);
CategoryTableBackup.Merge(SubTable);
//SubTable is the DataTable with the new entries
CategoryAdapterBackup.Update(CategoryTableBackup);
I'm having a problem discerning your intentions with this code. Why not simply use sqlbulkcopy on SubTable? That would append the contents of SubTable to the destination SQL table. If you are afraid of duplicates, then insert the contents of SubTable Table to a Temp in the DB and maybe use a Join to insert rows into the destination table where not exists row in destination table.
Try with CategoryAdapterBackup.Flush() or with DBManager.Flush()
also, could be a good idea replace SELECT*FROM by SELECT * FROM (with spaces)

how to add new datatable to dataset at first position

i have one dataset with 3 data tables again i have to add one more data table in same dataset at first position(Ex:mydataset.tables[0]th position) .can any one help me regarding this.
You will probably need to pull all the datatables out of the dataset into a list, get them in the right order, and then re-add them all to the dataset since you cannot insert to or modify the existing order:
var tables = new DataTable[4];
tables[0] = mynewtable;
tables[1] = mydataset.Tables[0];
tables[2] = mydataset.Tables[1];
tables[3] = mydataset.Tables[2];
mydataset.Tables.Clear();
mydataset.Tables.Add(Tables[0]);
mydataset.Tables.Add(Tables[1]);
mydataset.Tables.Add(Tables[2]);
mydataset.Tables.Add(Tables[3]);

Why do I get empty results using generated code from DB?

I'm using SQL Server 2005. I have a table scores with 6 rows and columns - name, score and id.
I added the data source with VS and it generated a dataset called testDataSet.
So I tried the following code which gives me zero results:
testDataSet db = new testDataSet();
var result = from row in db.scores
select row.name;
Where is the problem?
The probem you are having is that you are querying an empty DataSet.
You first have to create a connection to your testDataSet and fill the tables contained in it with data from your database.
If you have created testDataSet with the automated tools VS provides then the tool will have also created the relevant TableDataAdapters (in their own namespace) to fill and update your DataSet.
Initialize the relevant TableDataAdapter and fetch the data from the database with the Fill(db) method.
you sould query dataTable like this:
DataTable products = ds.Tables["Product"];
var query = products.AsEnumerable().
Select(product => new
{
ProductName = product.Field<string>("Name"),
ProductNumber = product.Field<string>("ProductNumber"),
Price = product.Field<decimal>("ListPrice")
});
Try this code instead:
scoresTableAdapter adapter = new scoresTableAdapter();
var result = from row in adapter.GetData() select row.name;
Others are right that your problem is that you are not querying the data. When you generated the dataset, an adapter is also generated for you, that will help you to query the data as shown above.
The DataSet is just a structured container for the query results, it has no connection to the data source (database). In order to populate the DataSet with data you need to use a DataAdapter with a SelectCommand and call the Fill method.
var myConn = new SqlConnection ("..." );
var myAdapter = new SqlDataAdapter ( "SELECT * FROM TableName", myConn );
var myData = new testDataSet( );
myAdapter.Fill ( myData, "TableName" );

Categories

Resources