C# Dataset to Access DB - c#

I have a dataset that is dynamically created from a csv file. What I want to do is insert the rows into my MS Access table but I cannot figure out where to start with this.
The headers of the data in the dataset can vary as far as the order but the name of the header will always match the access database. Do I have to statically call out the header name in the insert command or can I build the headers from the dataset?
I know how to create the connection and open it to the database but am not sure how to create in insert command to dynamically pull the table headers.
I am pretty green when it comes to C# programming so if you can spell it out for me I would really appreciate it!
Here is an example of the access table headers:
ID, Item, Cost, Retail
Then the CSV which will fill the dataset table. It might have Retail or it might not:
Item, Cost
Here is the code I have so far but it doesn't write to the access table. If I vew the dtAccess it shows correctly.
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"C:\\Database.accdb\";Persist Security Info=False;");
myConnection.Open();
string queryString = "SELECT * from " + lblTable.Text;
OleDbDataAdapter adapter = new OleDbDataAdapter(queryString, myConnection);
DataTable dtAccess = new DataTable();
DataTable dtCSV = new DataTable();
dtCSV = ds.Tables[0];
using (new OleDbCommandBuilder(adapter))
{
adapter.Fill(dtAccess);
dtAccess.Merge(dtCSV);
adapter.Update(dtAccess);
}
myConnection.Close();

Figured it out. Here is the code I used:
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Database.accdb\";Persist Security Info=False;");
//command to insert each ASIN
OleDbCommand cmd = new OleDbCommand();
//command to update each column (ASIN, Retail... from CSV)
OleDbCommand cmd1 = new OleDbCommand();
//load csv data to dtCSV datatabe
DataTable dtCSV = new DataTable();
dtCSV = ds.Tables[0];
// Now we will collect data from data table and insert it into database one by one
// Initially there will be no data in database so we will insert data in first two columns
// and after that we will update data in same row for remaining columns
// The logic is simple. 'i' represents rows while 'j' represents columns
cmd.Connection = myConnection;
cmd.CommandType = CommandType.Text;
cmd1.Connection = myConnection;
cmd1.CommandType = CommandType.Text;
myConnection.Open();
for (int i = 0; i <= dtCSV.Rows.Count - 1; i++)
{
cmd.CommandText = "INSERT INTO " + lblTable.Text + "(ID, " + dtCSV.Columns[0].ColumnName.Trim() + ") VALUES (" + (i + 1) + ",'" + dtCSV.Rows[i].ItemArray.GetValue(0) + "')";
cmd.ExecuteNonQuery();
for (int j = 1; j <= dtCSV.Columns.Count - 1; j++)
{
cmd1.CommandText = "UPDATE " + lblTable.Text + " SET [" + dtCSV.Columns[j].ColumnName.Trim() + "] = '" + dtCSV.Rows[i].ItemArray.GetValue(j) + "' WHERE ID = " + (i + 1);
cmd1.ExecuteNonQuery();
}
}
myConnection.Close();

Access has hidden tables that provide database access to the tables and columns in the database. The names of them are dependent upon access version, but they're typically something like systables? It's been a while, but if you "show hidden tables" you should be able to find them.

If the the two datatable have the same structure you can merge the "CSV" Datatable with the Database table datatable, so for example you can retrieve the database table into a datatable using a data adapter :
string queryString = "SELECT * FROM sometable";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataTable dtAccess = new DataTable();
adapter.Fill(dtAccess);
then you can merge the content of this DataTable with the content of the CSV DataTable :
dtAccess.Merge(dtCSV);
After that you can write the content of the datatable into the access database table with a command builder :
using (new SqlCommandBuilder(adapter)) {
adapter.Update(dtAccess);
}
If the datatables have the same structure should work without any problem ...

Related

what i write inside loop to display similar item code on datagridview and insert different itemcode on database sql server

Problem
what i write inside loop to display similar item code on datagridview and insert different itemcode on database sql server .
SQL Server Database(2014) Items Table
ItemCode(pk) ItemName
001 mouse
002 keyboard
003 Headphone
On File Excel sheet 2010
ItemCode ItemName
001 mouse
002 keyboard
004 screen
005 Ram
Actually i need when import excel file insert different items code that not exist
on sql server database and Exist Items On Database and Found on Excel not insert but display on datagridview .
according to my case insert itemcodes 004,005 on table Items.
and show 001,002 in grid view as exist items .
my function as below
my code (Inside Loop)
public static void ImportFromExcelToDataBase()
{
Datatable dt = ShowExcelData();
DataTable dtItems = GetSqlItems();
for (int i = 0; i < dt.Rows.Count; i++)
{
//what i write here
// if itemcode exist on excel exist on sql server database
then display similar items exist on database and excel as 001,002 on datagridview
//else
// do insert data
string Insert = "Insert Into Values (" + data + ")";
DataAccess.ExecuteNonQuery(Insert);
}
}
public DataTable ShowExcelData()
{
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", txtpath.Text);
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
DataTable dt = new DataTable();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dt.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand com = new OleDbCommand();
com.Connection = con;
com.CommandText = #"SELECT [ItemCode],[ItemsName],[ItemAddress] FROM [" + SheetName + "] ";
OleDbDataAdapter oledbda = new OleDbDataAdapter();
oledbda.SelectCommand = com;
DataSet ds = new DataSet();
oledbda.Fill(ds);
dt = ds.Tables[0];
con.Close();
return dt;
}
dt = ShowExcelData();
public DataTable GetSqlItems()
{
string GetItems = #"select ItemCode,ItemsName,ItemAddress from Items";
DataTable tbGetItems = DataAccess.ExecuteDataTable(GetItems );
return tbGetItems ;
}
dtItems = GetSqlItems();
make ItemCode to primary key, your command will fail, then offcourse u know what are exist items

How to make insert operation using MySqlDataAdapter in ASP.NET

I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
// con.Open();
// MySqlCommand cmd = con.CreateCommand();
// cmd.CommandType = CommandType.Text;
// cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
// cmd.ExecuteNonQuery();
// con.Close();
Help with suggestions.
To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record
However if you really want to try to use an DataAdapter then you need this code
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
// This is important, because Update will work only on rows
// present in the DataTable whose RowState is Added, Modified or Deleted
dt.Rows.Add(sid, sname);
da.Update(dt);
}

SQL Query runs only once

I have the following code:
SqlConnection con = new SqlConnection(#"Data Source=NUC\MICROGARDE;Initial Catalog=SQL;Integrated Security=True");
String Query;
for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
MessageBox.Show(" " + this.dataGridView1.Columns.Count);
MessageBox.Show(" " + this.dataGridView1.Columns[i].Name + " ");
MessageBox.Show(" " + this.dataGridView1.SelectedRows[0].Cells[i].Value + " ");
Query = "insert into [" + this.comboBox1.Text + "] ([" + this.dataGridView1.Columns[i].Name + "]) Values ('" + this.dataGridView1.SelectedRows[0].Cells[i].Value + "') ;";
SqlCommand cmd = new SqlCommand(Query, con);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(Query, con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.DataSource = bSource;
}
con.Close();
It should insert a specific value into EVERY column of a table (shown in a dataGridView), but after it saves the first value (the value from the first column of the row that we want to insert) it refreshes the table and only that first value gets inserted... I want to insert the whole row
the code is behaving correctly as expected.
here is your code:
for each column
build sql string to take first row, current column and insert in db
create sql command using the above sql string
execute the above command
refresh datagrid
next
the above produces the exact behaviour you are experiencing, this is expected and correct in the sense that the code does exactly what it is told to do.
what your code should be based on your description:
for each row
build base sql statement
for each column
add current value and field name to the base statement
next
create sql command
fill the command with the statement built in the previous cycle
execute the sql statement
next
refresh datagrid
if you have to insert only one row then the outer foreach is not needed
while performing string concatenation to build the statements take care of input sanitization and datatypes.
con.open() should be outside the loop

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