Transfer tables from one MS Access database to another using C# - c#

I have two almost same databases (both are *.mdb), but one of them has few new tables. Now I can only detect tables, that should be imported, using code below:
public static List<string> GetDBTables(string path)
{
List<string> allTables = new List<string>();
String connect = ("Provider=Microsoft.JET.OLEDB.4.0;data source="
+ path + ";Persist Security Info=False;");
OleDbConnection con = new OleDbConnection(connect);
con.Open();
DataTable tables = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] { null, null, null, "TABLE" });
int counter = 1;
foreach (DataRow row in tables.Rows)
{
allTables.Add(row[2].ToString());
counter++;
}
con.Close();
return allTables;
}
var withNewTables = GetDBTables(".\\one.mdb");
var withoutNewTables = GetDBTables(".\\another.mdb");
var NotFoundTables = withNewTables.Except(withoutNewTables).ToList();
How can I import these tables in the old database using C #?

Access SQL offers two features which are useful here.
SELECT <field list> INTO NewTable
FROM table_name IN 'path to other db file'
So I can execute this statement from an OleDb connection to my destination db file, and it will create tblFoo_copy from the data contained in tblFoo in the other db file, NewData.mdb.
SELECT f.* INTO tblFoo_copy
FROM tblFoo AS f IN 'C:\Users\hans\Documents\NewData.mdb';
Build and execute similar statements for each of those tables you want to import.

Well, in addition to HansUp answer, I post the implementation of this on C#:
public static void insertTables(string path_from, string path_to,
List<string> _tables)
{
string conString = ("Provider=Microsoft.JET.OLEDB.4.0;data source="
+ path_to + ";Persist Security Info=False;");
OleDbConnection dbconn = new OleDbConnection(conString);
dbconn.Open();
OleDbCommand dbcommand = new OleDbCommand();
_tables.ForEach(delegate(String name)
{
string selQuery = "SELECT f.* INTO " + name + " FROM " + name
+ " AS f IN '" + path_from + "';";
dbcommand.CommandText = selQuery;
dbcommand.CommandType = CommandType.Text;
dbcommand.Connection = dbconn;
int result = dbcommand.ExecuteNonQuery();
});
dbconn.Close();
}
insertTables(".\\one.mdb", ".\\another.mdb", NotFoundTables);

Related

Retrieving data from xlsx using OleDb(C#), how to get the count of lines in the xlsx?

My final goal is to retrieve the data from .xlsx file and load them into .mdb (Microsoft Access) file. My code is now like this:
String fileName = "1.xlsx";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"");
conn.Open();
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string cmdText = "SELECT * FROM [sheet1$A3:B3]";
DataSet ds;
using (OleDbCommand cmd = new OleDbCommand(cmdText))
{
cmd.Connection = conn;
OleDbDataAdapter adpt = new OleDbDataAdapter(cmd);
ds = new DataSet();
adpt.Fill(ds, "sheet1");
}
But this is when I know how many lines are there in the sheet. What if I don't know about this information? Can I somehow manage to know how many lines are there in the sheet?
change the line
string cmdText = "SELECT * FROM [sheet1$A3:B3]";
to
string cmdText = "SELECT * FROM [sheet1$]";
and add the following line to at the end of your code.
int numberOfRows = ds.Tables[0].Rows.Count;
You don't need to assign columns and rows. You cold just do something like:
string cmdText = "SELECt * FROM [sheet1$]"
Or if you want to limit which columns to read:
string cmdText = "SELECt * FROM [sheet1$A1:B100000]"
Edit: Sorry, missed the part about needing to know how many rows there are. cilerler has your answer.

How can i export gridview into MS Access(.mdb) in C#

My question is how can i export gridview into MS Access in C#
for this I am Using the following code:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
//Make adapters for each table we want to export
SqlDataAdapter adapter1 = new SqlDataAdapter();
// SqlDataAdapter adapter2 = new SqlDataAdapter();
DataTable dtFillGrid = (DataTable)ViewState["FillGrid"];
//Fills the data set with data from the SQL database
// DataSet dataSet = new DataSet();
adapter1.Fill(dtFillGrid);
// adapter2.Fill(dataSet, "Table2");
//Create an empty Access file that we will fill with data from the data set
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
//Create an Access connection and a command that we'll use
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
//This loop creates the structure of the database
foreach (DataTable table in dtFillGrid.Rows)
{
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns)
{
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows)
{
foreach (DataRow row in table.Rows)
{
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray)
{
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
accessConnection.Close();
but in this code I get an error:
The Type or Namespace name ADOX could not be found
According to accessConnectionString content you should install "Data Connectivity Components" in your machine.
It is available to download at http://www.microsoft.com/en-us/download/details.aspx?id=23734
You need to add a reference for Microsoft ADO Ext. 2.7 for DDL and Security(the version number may be different though) which can be found under the COM section of the references dialog , and then add using ADOX; in your code.
Here I did not export gridview in MS Access but I made a database in MS Access using C# with the help of this code
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;

How can I export GridView to MS Access in C#

I want to export grid to MS Access in C#
Here's the code that I've tried:
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = ConfigurationManager.ConnectionStrings["College"].ConnectionString;
SqlDataAdapter adapter1 = new SqlDataAdapter();
adapter1.Fill(dtFillGrid);
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
foreach (DataTable table in dtFillGrid.Rows) {
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns) {
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dtFillGrid.Rows) {
foreach (DataRow row in table.Rows) {
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray) {
commandText += "'" + item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText; command.ExecuteNonQuery();
}
}
accessConnection.Close();
How can I do this?
I would suggest you create the MDB database, create the table(s) you want using sql, then at runtime bind the gridview, or loop through the results and do a batch import.
See here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms677200(v=vs.85).aspx
using ADOX; // add a COM reference to "Microsoft ADO Ext. x.x for DDL and Security"
static void CreateMdb(string fileNameWithPath)
{
ADOX.Catalog cat = new ADOX.Catalog();
string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5";
cat.Create(String.Format(connstr, fileNameWithPath));
cat = null;
}
if you dont have problem with payement you can use 'Spire doc' to save datagrid into msAccess like so :
private void btnExportToAccess_Click(object sender, EventArgs e)
{
Spire.DataExport.Access.AccessExport accessExport = new
Spire.DataExport.Access.AccessExport();
accessExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
accessExport.DataTable = this.dataGridView1.DataSource as DataTable;
accessExport.DatabaseName = #"..\..\ToMdb.mdb";
accessExport.TableName = "ExportFromDatatable";
accessExport.SaveToFile();
}
and Here a link where you can find more clarification
Here I am not export gridview in MS Access but I made a database in MS Access by using C# with the help of this code:
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;
Yes I tell you to all of you that we don't need to export data by gridview to MS Access , we can do this directly create database in MS Access using C#

Export MSSQL database to MS Access .accdb file

I have a Microsoft SQL Server database which is updated with data regularly. I would like to store this database with all tables (and preferrably relationsships) to a new Microsoft Access (.accdb) file using C#.
SQL Management Studio is installed on the system so I think one solution could be to invoke BCP (http://msdn.microsoft.com/en-us/library/ms162802.aspx) from the code, but I haven't figured out how to use it correctly in this case. I guess there are much better ways doing it without using BCP though.
Can anyone recommend a way to achieve this?
Thank you
You can import MSSQL Data in Access; More info on: http://office.microsoft.com/en-us/access-help/import-or-link-to-sql-server-data-HA010200494.aspx
Update:
Alternately you can select all tables using sqldataadapter to store everything in a dataset, see: Obtaining a dataset from a SQL Server database
From there on you can save the dataset as a access database file, see: C# Dataset to Access DB
Maybe this is more inline with your problem.
Thanks to Ferdy's suggestion I solved the problem. Since it could be of use for others I put my working code sample here:
//The connection strings needed: One for SQL and one for Access
String accessConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\...\\test.accdb;";
String sqlConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Your_Catalog;Integrated Security=True";
//Make adapters for each table we want to export
SqlDataAdapter adapter1 = new SqlDataAdapter("select * from Table1", sqlConnectionString);
SqlDataAdapter adapter2 = new SqlDataAdapter("select * from Table2", sqlConnectionString);
//Fills the data set with data from the SQL database
DataSet dataSet = new DataSet();
adapter1.Fill(dataSet, "Table1");
adapter2.Fill(dataSet, "Table2");
//Create an empty Access file that we will fill with data from the data set
ADOX.Catalog catalog = new ADOX.Catalog();
catalog.Create(accessConnectionString);
//Create an Access connection and a command that we'll use
OleDbConnection accessConnection = new OleDbConnection(accessConnectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = accessConnection;
command.CommandType = CommandType.Text;
accessConnection.Open();
//This loop creates the structure of the database
foreach (DataTable table in dataSet.Tables)
{
String columnsCommandText = "(";
foreach (DataColumn column in table.Columns)
{
String columnName = column.ColumnName;
String dataTypeName = column.DataType.Name;
String sqlDataTypeName = getSqlDataTypeName(dataTypeName);
columnsCommandText += "[" + columnName + "] " + sqlDataTypeName + ",";
}
columnsCommandText = columnsCommandText.Remove(columnsCommandText.Length - 1);
columnsCommandText += ")";
command.CommandText = "CREATE TABLE " + table.TableName + columnsCommandText;
command.ExecuteNonQuery();
}
//This loop fills the database with all information
foreach (DataTable table in dataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
String commandText = "INSERT INTO " + table.TableName + " VALUES (";
foreach (var item in row.ItemArray)
{
commandText += "'"+item.ToString() + "',";
}
commandText = commandText.Remove(commandText.Length - 1);
commandText += ")";
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
accessConnection.Close();

Import data from excel to mysql using c#

I have Excel file shown bellow
I want to read 1st read only all school names & school address & insert them in SchoolInfo table of mySql database.
After that I want to read data for each school & insert it in StudentsInfo table which has foreign key associated with SchoolInfo table.
I am reading excel sheet something like this.
public static void Import(string fileName)
{
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +
";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";
var output = new DataSet();
using (var conn = new OleDbConnection(strConn))
{
conn.Open();
var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
if (dt != null)
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString();
var cmd = new OleDbCommand("SELECT * FROM [+"+sheet+"+]", conn);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter xlAdapter = new OleDbDataAdapter(cmd);
xlAdapter.Fill(output,"School");
}
}
}
Now I am having data in datatable of dataset, Now how do I read desired data & insert it in my sql table.
Try the following steps:
Reading from Excel sheet
First you must create an OleDB connection to the Excel file.
String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + path + ";" +
"Extended Properties=Excel 8.0;";
OleDbConnection xlConn = new OleDbConnection(connectionString);
xlConn.Open();
Here path refers to the location of your Excel spreadsheet. E.g. "D:\abc.xls"
Then you have to query your table. For this we must define names for the table and columns first. Click here to find out how.
Now create the command object.
OleDbCommand selectCmd = new OleDbCommand("SELECT * FROM [Sheet1$]", xlConn);
Now we have to store the ouput of the select command into a DataSet using a DataAdapter
OleDbDataAdapter xlAdapter = new OleDbDataAdapter();
objAdapter1.SelectCommand = selectCmd;
DataSet xlDataset = new DataSet();
xlAdapter.Fill(xlDataset, "XLData");
Save the data into variables
Now extract cell data into variables iteratively for the whole table by using
variable = xlDataset.Tables[0].Rows[row_value][column_value].ToString() ;
Write the data from the variables into the MySQL database
Now connect to the MySQL database using an ODBC connection
String mySqlConnectionString = "driver={MySQL ODBC 5.1 Driver};" +
"server=localhost;" + "database=;" + "user=;" + "password=;";
OdbcConnection mySqlConn = new OdbcConnection(mySqlConnectionString);
mySqlConn.Open();
Construct your INSERT statement using the variables in which data has been stored from the Excel sheet.
OdbcCommand mySqlInsert = new OdbcCommand(insertCommand, mySqlConn);
mySqlInsert.ExecuteScalar()

Categories

Resources