I have two Access 2003 databases (fooDb and barDb). There are four tables in fooDb that are linked to tables in barDb.
Two questions:
How do I update the table contents (linked tables in fooDb should be synchronized with the table contents in barDb)
How do I re-link the table to a different barDb using ADO.NET
I googled but didn't get any helpful results. What I found out is how to accomplish this in VB(6) and DAO, but I need a solution for C#.
Here is my solution to relinking DAO tables using C#.
My application uses a central MS Access database and 8 actual databases that are linked in.
The central database is stored locally to my C# app but the application allows for the 8 data databases to be located elsewhere. On startup, my C# app relinks DAO tables in the central database based on app.config settings.
Aside note, this database structure is the result of my app originally being a MS Access App which I ported to VB6. I am currently converting my app to C#. I could have moved off MS Access in VB6 or C# but it is a very easy to use desktop DB solution.
In the central database, I created a table called linkedtables with three columns TableName, LinkedTableName and DatabaseName.
On App start, I call this routine
Common.RelinkDAOTables(Properties.Settings.Default.DRC_Data
, Properties.Settings.Default.DRC_LinkedTables
, "SELECT * FROM LinkedTables");
Default.DRC_Data - Current folder of central access DB
Default.DRC_LinkedTables - Current folder of 8 data databases
Here is code does the actual relinking of the DAO Tables in C#
public static void RelinkDAOTables(string MDBfile, string filepath, string sql)
{
DataTable linkedTables = TableFromMDB(MDBfile, sql);
dao.DBEngine DBE = new dao.DBEngine();
dao.Database DB = DBE.OpenDatabase(MDBfile, false, false, "");
foreach (DataRow row in linkedTables.Rows)
{
dao.TableDef table = DB.TableDefs[row["Name"].ToString()];
table.Connect = string.Format(";DATABASE={0}{1} ;TABLE={2}", filepath, row["database"], row["LinkedName"]);
table.RefreshLink();
}
}
Additional code written to fetch data from a access database and return it as a DataTable
public static DataTable TableFromOleDB(string Connectstring, string Sql)
{
try
{
OleDbConnection conn = new OleDbConnection(Connectstring);
conn.Open();
OleDbCommand cmd = new OleDbCommand(Sql, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
catch (OleDbException)
{
return null;
}
}
public static DataTable TableFromMDB(string MDBfile, string Sql)
{
return TableFromOleDB(string.Format(sConnectionString, MDBfile), Sql);
}
If you're coding in C#, then Access is not involved, only Jet. So, you can use whatever method you want to access the data and then code the updates.
I've coded this kind of thing in Access many times, and my approach for each table is:
run a query that deletes from fooDB that no longer exist in barDB.
run a query that inserts into fooDB records that are in barDB that do not yet exist in fooDB.
I always use code that writes on-the-fly SQL to update the fooDB table with the data from barDB.
The 3rd one is the hard one. I loop through the fields collection in DBA and write SQL on the fly that would be something like this:
UPDATE table2 INNER JOIN table1 ON table2.ID = table1.ID
SET table2.field1=table1.field1
WHERE (table2.field1 & "") <> (table1.field1 & "")
For numeric fields you'd have to use your available SQL dialect's function for converting Null to zero. Running Jet SQL, I'd use Nz(), of course, but that doesn't work via ODBC. Not sure if it will work with OLEDB, though.
In any event, the point is to issue a bunch of column-by-column SQL updates instead of trying to do it row by row, which will be much less efficient.
Related
I have two databases, one is Oracle 11g and the other is in Sql Server 2012. There is a table in the Oracle database that contains a column called BASE_ID. This is comprised of work order numbers.
In the Sql Server database, there is also a table that contains a column called WorkOrders. This also contains work order numbers. What I need to do is compare what is in the Oracle column to what is in the SQL Server column, and display what is in Oracle but not in Sql Server. I am a little stumped here, even for a starting point. I am kind of just taking pot shots. This mess is what I have so far:
private void compare()
{
try
{
if (con.State != ConnectionState.Open)
con.Open();
DataTable t = new DataTable();
OracleCommand oraCmd = new OracleCommand("SELECT BASE_ID FROM WORK_ORDER x WHERE NOT EXISTS(SELECT NULL FROM [SQLServer].[BACRTest].[WorkOrders] y WHERE y.WorkOrder = x.BASE_ID)", oraconn);
OracleDataAdapter dt = new OracleDataAdapter(oraCmd);
dt.Fill(t);
dataGridView3.DataSource = t;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
This is just throwing me an ORA-00903: invalid table name error which is fair enough because I wasn't really expecting it to work.
Any suggestions would be very much appreciated.
As noted above, if you have the correct products installed (e.g. Oracle's Database Gateway for SQL Server, or Database Gateway for ODBC) you can make a direct connection between Oracle and SQL Server. If you don't have such products you can try exporting the SQL Server table to a comma-separated values (.csv) file, then set up an external table in Oracle to read the .csv. Not perhaps the most seamless method in the world, but it does represent one way to handle this.
Best of luck.
Because the entries are on different DBMSs, you cannot directly make a query for this, so most likely you will need to store the entries in memory and compare them one by one. Maybe you could partition the tables into small sets and compare them
Hi I have a DataSet in C# which contains 3 DataTables. Two of the tables: SummaryLocal_Bands and SummaryLocal_Averages contain an fk relationship to the pk in the 3rd table: SummaryLocal. The tables in Sql Server have the same structure, columns, relationships, etc as the tables in this DataSet. Lets say I add rows to the DataTables in the DataSet so that they contain data. I then want to Insert their rows into the sql server tables (which contain the same structure as the datatables in the dataset as noted above). How hard is this to accomplish and how do I accomplish it? Or is it smarter to accomplish this another way?
Is seems like you want to persist the changes on your DataTables to it's underlying tables in the database..can't you just make a connection to database and make an insert statement?...
Try creating a method that have the following commands below: (Note: it's just a skeleton of the commands that you need to do, fill them up according to your settings)
string connectionString = "your_connection_string";
SqlConnection con = new SqlConnection(connectionString);
try
{
con.Open();
string query = "insert statement";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#some_parameter", "value_of_some_parameter");
cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
throw;
}
Or, if your datatables are somehow not connected to a database, you can still use the above method by looping through the contents of your datatable.
In C# I want to execute a query that use 2 different databases (One is Access for local, and other is distant and is MySQL)
I'm able to do it in VBA Access, but how I can make the same thing in C# ??
This is how I made it in Access:
Link my 2 differents table/databases in Table
In VBA:
sSQL = "INSERT INTO DB1tblClient SELECT * FROM DB2tblClient"
CurrentDb.Execute sSQL
How I can execute this SQL in C# ? (What object to use, etc... Example code if you can)
Thanks !
There are two ways to do this. One is to set up linked tables on Access and run a single query. The other is to run both queries from c# and join them with linq.
The first way is better. If you really have to do it with linq, here is some sample code:
dWConnection.Open();
dWDataAdaptor.SelectCommand = dWCommand1;
dWDataAdaptor.Fill(queryResults1);
dWDataAdaptor.SelectCommand = dWCommand2;
dWDataAdaptor.Fill(queryResults2);
dWConnection.Close();
IEnumerable<DataRow> results1 = (from events in queryResults1.AsEnumerable()
where events.Field<string>("event_code").ToString() == "A01"
|| events.Field<string>("event_code").ToString() == "ST"
select events ) as IEnumerable<DataRow>;
var results2 = from events1 in queryResults1.AsEnumerable()
join events2 in queryResults2.AsEnumerable()
on (string)events1["event_code"] equals (string)events2["event_code"]
select new
{
f1 = (string)events1["event_code"],
f2 = (string)events2["event_name"]
};
DataTable newDataTable = new DataTable();
newDataTable = results1.CopyToDataTable<DataRow>();
See why I said linked tables is better?
You should be able to run the same SQL command from any app, really. This is assuming:
You're connecting to Access from your C# app
DB1tblClient is a local Access table
DB2tblClient is a link table in Access
Given these, you might try the following:
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Stuff\MyAccessdb.mdb"))
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO DB1tblClient SELECT * FROM DB2tblClient";
cmd.ExecuteNonQuery();
}
}
You might want to check connectionstrings.com if you can't get the connection string right, and you may need to install some components (MDAC or ACE) for connections that use those providers.
Well it is not possible to run this such complex query with single statement.
Basically each query execution object initialized by particular database information,
so need two different object for each database first think.
Now 2 Object need with initialized with its own connection object.
Just fetch data by first object and insert it to another database by usin second connection object.
You need to keep following points in mind before trying this type of query
Both the databases are accessible from your code.
There is inter-connectivity between both the database.
Both the databases are available for the user that you are using to execute this query.
You need to specify the query in following format
DATABASE_NAME.SCHEMA_NAME.TABLE_NAME instead of just TABLE_NAME
EDIT
If you don't have inter-connectivity between databases you can follow following steps
Connect to Source database using one connection.
Read the data from source database into a dataset or datatable using SELECT query.
Connect to target database using a second connection.
Insert all the records one by one using a loop to TARGET Database using standard INSERT query
I'm trying to send a DataTable to a stored procedure using c#, .net 2.0 and SQLServer 2012 Express.
This is roughly what I'm doing:
//define the DataTable
var accountIdTable = new DataTable("[dbo].[TypeAccountIdTable]");
//define the column
var dataColumn = new DataColumn {ColumnName = "[ID]", DataType = typeof (Guid)};
//add column to dataTable
accountIdTable.Columns.Add(dataColumn);
//feed it with the unique contact ids
foreach (var uniqueId in uniqueIds)
{
accountIdTable.Rows.Add(uniqueId);
}
using (var sqlCmd = new SqlCommand())
{
//define command details
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = "[dbo].[msp_Get_Many_Profiles]";
sqlCmd.Connection = dbConn; //an open database connection
//define parameter
var sqlParam = new SqlParameter();
sqlParam.ParameterName = "#tvp_account_id_list";
sqlParam.SqlDbType = SqlDbType.Structured;
sqlParam.Value = accountIdTable;
//add parameter to command
sqlCmd.Parameters.Add(sqlParam);
//execute procedure
rResult = sqlCmd.ExecuteReader();
//print results
while (rResult.Read())
{
PrintRowData(rResult);
}
}
But then I get the following error:
ArgumentOutOfRangeException: No mapping exists from SqlDbType Structured to a known DbType.
Parameter name: SqlDbType
Upon investigating further (in MSDN, SO and other places) it appears as if .net 2.0 does not support sending a DataTable to the database (missing things such as SqlParameter.TypeName), but I'm still not sure since I haven't seen anyone explicitly claiming that this feature is not available in .net 2.0
Is this true?
If so, is there another way to send a collection of data to the database?
Thanks in advance!
Out of the box, ADO.NET does not suport this with good reason. A DataTable could take just about any number of columns, which may or may not map up to a real table in your database.
If I'm understanding what you want to do - upload the contents of a DataTable quickly to a pre-defined, real table with the same structure, I'd suggest you investigate SQLBulkCopy.
From the documentation:
Microsoft SQL Server includes a popular command-prompt utility named
bcp for moving data from one table to another, whether on a single
server or between servers. The SqlBulkCopy class lets you write
managed code solutions that provide similar functionality. There are
other ways to load data into a SQL Server table (INSERT statements,
for example), but SqlBulkCopy offers a significant performance
advantage over them.
The SqlBulkCopy class can be used to write data only to SQL Server
tables. However, the data source is not limited to SQL Server; any
data source can be used, as long as the data can be loaded to a
DataTable instance or read with a IDataReader instance.
SqlBulkCopy will fail when bulk loading a DataTable column of type
SqlDateTime into a SQL Server column whose type is one of the
date/time types added in SQL Server 2008.
However, you can define Table Value Parameters in SQL Server in later versions, and use that to send a Table (DateTable) in the method you're asking. There's an example at http://sqlwithmanoj.wordpress.com/2012/09/10/passing-multipledynamic-values-to-stored-procedures-functions-part4-by-using-tvp/
Per my experience, if you're able to compile the code in C# that means the ADO.Net support that type. But if it fails when you execute the code then the target database might not support it. In your case you mention the [Sql Server 2012 Express], so it might not support it. The Table Type was supported from [Sql Server 2005] per my understanding but you had to keep the database compatibility mode to greater than 99 or something. I am 100% positive it will work in 2008 because I have used it and using it extensively to do bulk updates through the stored procedures using [User Defined Table Types] (a.k.a UDTT) as the in-parameter for the stored procedure. Again you must keep the database compatibility greater than 99 to use MERGE command for bulk updates.
And of course you can use SQLBulkCopy but not sure how reliable it is, is depending on the
I am working on moving a database from MS Access to sql server. To move the data into the new tables I have decided to write a sync routine as the schema has changed quite significantly and it lets me run testing on programs that run off it and resync whenever I need new test data. Then eventually I will do one last sync and start live on the new sql server version.
Unfortunately I have hit a snag, my method is below for copying from Access to SQLServer
public static void BulkCopyAccessToSQLServer
(string sql, CommandType commandType, DBConnection sqlServerConnection,
string destinationTable, DBConnection accessConnection, int timeout)
{
using (DataTable dt = new DataTable())
using (OleDbConnection conn = new OleDbConnection(GetConnection(accessConnection)))
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
cmd.CommandType = commandType;
cmd.Connection.Open();
adapter.SelectCommand.CommandTimeout = timeout;
adapter.Fill(dt);
using (SqlConnection conn2 = new SqlConnection(GetConnection(sqlServerConnection)))
using (SqlBulkCopy copy = new SqlBulkCopy(conn2))
{
conn2.Open();
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BulkCopyTimeout = timeout;
copy.WriteToServer(dt);
copy.NotifyAfter = 1000;
}
}
}
Basically this queries access for the data using the input sql string this has all the correct field names so I don't need to set columnmappings.
This was working until I reached a table with a calculated field. SQLBulkCopy doesn't seem to know to skip the field and tries to update the column which fails with error "The column 'columnName' cannot be modified because it is either a computed column or is the result of a union operator."
Is there an easy way to make it skip the calculated field?
I am hoping not to have to specify a full column mapping.
There are two ways to dodge this:
use the ColumnMappings to formally define the column relationship (you note you don't want this)
push the data into a staging table - a basic table, not part of your core transactional tables, whose entire purpose is to look exactly like this data import; then use a TSQL command to transfer the data from the staging table to the real table
I always favor the second option, for various reasons:
I never have to mess with mappings - this is actually important to me ;p
the insert to the real table will be fully logged (SqlBulkCopy is not necessarily logged)
I have the fastest possible insert - no constraint checking, no indexing, etc
I don't tie up a transactional table during the import, and there is no risk of non-repeatable queries running against a partially imported table
I have a safe abort option if the import fails half way through, without having to use transactions (nothing has touched the transactional system at this point)
it allows some level of data-processing when pushing it into the real tables, without the need to either buffer everything in a DataTable at the app tier, or implement a custom IDataReader