Bulk import from MS Access and Insert into Sql Server [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to read records from MS Access database and Insert into Sql server database, the process should be bulk insertion. I'm using asp.net/vb.net

First of all read data from Excel sheet
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/temp/") + "FileName.xlsx; Extended Properties=Excel 12.0;";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT ColumnNames FROM [Sheet1$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
DataTable dtbl = new DataTable();
adapter.Fill(dtbl);
// Then use SQL Bulk query to insert those data
if (dtbl.Rows.Count > 0)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destConnection))
{
bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
bulkCopy.ColumnMappings.Add("ColumnName", "ColumnName");
bulkCopy.DestinationTableName = "DBTableName";
bulkCopy.WriteToServer(dtblNew);
}
}

private void Synchronize()
{
SqlConnection con = new SqlConnection("Database=DesktopNotifier;Server=192.168.1.100\\sql2008;User=common;Password=k25#ap;");
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("SELECT * FROM CustomerData", con);
DataSet ds = new DataSet();
adap.Fill(ds, "CustomerData");
DataTable dt = new DataTable();
dt = ds.Tables["CustomerData"];
foreach (DataRow dr in dt.Rows)
{
string File = dr["CustomerFile"].ToString();
string desc = dr["Description"].ToString();
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=D:\\DesktopNotifier\\DesktopNotifier.accdb";
OleDbConnection conn = new OleDbConnection(conString);
conn.Open();
string dbcommand = "insert into CustomerData (CustomerFile, Description) VALUES ('" + File + "', '" + desc + "')";
OleDbCommand mscmd = new OleDbCommand(dbcommand, conn);
mscmd.ExecuteNonQuery();
}
}
private void Configuration_Load(object sender, EventArgs e)
{
LoadGridData();
LoadSettings();
}

Just my two cents...
Using code like this:
DataSet ds = new DataSet();
adap.Fill(ds, "CustomerData");
You should be aware the the data adapter fill method is going to READ ALL data into memory. So if you have zillions of rows... think twice.

Related

SQL Parameter as table doesn't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to return a DataTable with this method but SqlParameter is not working properly.
private DataTable GetTable(string tableName)
{
const string queryString = "SELECT * FROM #TABLE";
SqlCommand sqlCommand = new SqlCommand(queryString, _sqlConnection);
SqlParameter sqlParameter = new SqlParameter("#TABLE", SqlDbType.Text)
{
Value = tableName
};
sqlCommand.Parameters.Add(sqlParameter);
_sqlConnection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
_sqlConnection.Close();
dataAdapter.Dispose();
dataGridViewTable.DataSource = dataTable;
dataGridViewTable.AutoResizeColumns();
return dataTable;
}
I am sure connection is successful. Another method is working. This one doesn't. It throws a SqlException.
You can't pass a table name as a parameter. Also, use using to easily close/dispose of disposable resources.
Try this...
private DataTable GetTable(string tableName)
{
string queryString = "SELECT * FROM [" + tableName + "]";
DataTable dataTable = new DataTable(tableName);
using (SqlCommand sqlCommand = new SqlCommand(queryString, _sqlConnection))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand))
{
_sqlConnection.Open();
dataAdapter.Fill(dataTable);
_sqlConnection.Close();
}
dataGridViewTable.DataSource = dataTable;
dataGridViewTable.AutoResizeColumns();
return dataTable;
}
EDIT: Added square brackets around table name in query to handle names with spaces.

How do I copy an Excel column name to a string using OLEDB with C#? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Rookie here... I need to get the column name from an excel file so I can use it as a string. I'm using C# with OLEDB.
private void CheckFiles();
{
OleDbConnection MyConnection;
DataSet DtSet;
OleDbDataAdapter MyCommand;
string file = #"C:\Users\...path...\2015.xlsm";
MyConnection = new OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source='" +
file + "';Extended Properties=Excel 8.0;");
MyCommand = new OleDbDataAdapter("Select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = " +
tab, MyConnection);
MyConnection.Open();
MyCommand.TableMappings.Add("Table", "Net-informations.com");
MyConnection.Close();
}
Thanks in advance!
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;";
ConnectionString = string.Format(ConnectionString, #"FullPathToExcelFile"); //my path replace with your actual file path
OleDbConnection conn = new OleDbConnection(ConnectionString);
conn.Open();
OleDbCommand cmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
OleDbDataAdapter oleDBAdapter = new OleDbDataAdapter();
oleDBAdapter.SelectCommand = cmdSelect;
DataSet myDataset = new DataSet();
oleDBAdapter.Fill(myDataset);
conn.Close();

ms access database connection in a datagridview

What is the error of this code
connect = new OleDbConnection(coo);
connect.Open();
command.Connection = connect;
DataTable dt = new DataTable();
OleDbDataAdapter ODA = new OleDbDataAdapter("SELECT * FROM Items where itemno = '" + textBox1.Text + "'", connect);
ODA.Fill(dt);
dataGridView1.DataSource = dt;
after I run it, this is what happened
"Data type mismatch in criteria expression"
What should I do?
itemno is integer, that is why you are getting the error, remove the single quotes around the value. But, More importantly, Use Parameters with your query. You are prone to SQL Injection
using (var connect = new OleDbConnection(coo))
{
using (OleDbCommand command = new OleDbCommand("SELECT * FROM Items where itemno = ?", connect))
{
command.Parameters.Add(new OleDbParameter("#p1", OleDbType.Integer)
{
Value = textBox1.Text
});
DataTable dt = new DataTable();
OleDbDataAdapter ODA = new OleDbDataAdapter(command);
ODA.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Couple of things to add:
Enclose your Command and Connection object in using statement.
You don't have to explicitly open a connection with DataAdapter. It will open the connection to the database.
OleDB uses positional parameter instead of named parameter

Show content of tables in some textboxes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I wrote this code to show content of tables in SQL Server in a form in c# and those are displayed in a datagridview! If I want to show them in some textbox, what should I do?
SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=jadid;Integrated Security=True");
SqlCommand com_sel = new SqlCommand();
DataSet ds = new DataSet();
SqlDataAdapter adap = new SqlDataAdapter(com_sel);
com_sel.CommandText = "select * from t2 where same'" + textBox1.Text + "' ";
com_sel.CommandType = CommandType.text;
com_sel.Connection = con;
//com_sel.Parameters.Add("#p1", textBox1.Text);
con.Open();
ds.Clear();
adap.Fill(ds);
com_sel.ExecuteNonQuery();
dataGridView1.DataSource = ds.Tables[0];
for (i = 0; i < ds.Tables[0].Rows.Count - 1; i++) { textBox1.Text = ds.Tables[0].Rows[i]["Column"].ToString();
Check this code:
SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial
Catalog=jadid;Integrated Security=True");
SqlCommand com_sel = new SqlCommand();
DataSet ds = new DataSet();
SqlDataAdapter adap = new
SqlDataAdapter(com_sel);
com_sel.CommandText = "select * from t2 where id=1"; //
com_sel.CommandType = CommandType.StoredProcedure;
com_sel.Connection = con;
com_sel.Parameters.Add("#p1",textBox1.Text);
con.Open();
ds.Clear();
adap.Fill(ds);
com_sel.ExecuteNonQuery();
dataGridView1.DataSource = ds.Tables[0];
int i; //this way you display the data in the textbox
//TextBox1 is your textbox name
//lessthen:- less than sign not write
for(i=0;i lessthen ds.Tables[0].Rows.Count-1;i++) {
TextBox1.Text=ds.Tables[0].Rows[i]["Column"].ToString();
}

Insert Excel file data into database table using c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am developing on web application that will get the excel file using FileUpload control in asp.net c#. Now when click on submit button, i want to insert the excel data into my database table. I have database in SQL-Server. The field of database table & excel file are same.I want to insert that excel's data into my database table. So how can i do this?
Others have mentioned using Excel interop to read the Excel file in the comments, but this is NOT safe to do for a web application that may have multiple users.
To get started, have a look at the Excel Data Reader project. I've used this several times for processing Excel files from a web application and it works quite well.
You can use OLEDB classes to read directly from Excel file using the Excel drivers in OleDbConnection. Get the data in a datatable and save it to database.
string connectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\\testit.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Sheet1$]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
// Save your datatable records to DB as you prefer.
I've been testing NPOI as a replacement for another 3rd party Excel parsing library.
https://code.google.com/p/npoi/
So far it seems to work pretty well and have a very complete feature set. Of course, if all you need is very basic Excel data reading (and no writing), then the other DB connection style interfaces mentioned here should work well enough.
EDIT: added sample code
using( FileStream fs = new FileStream("file.xls", FileMode.Open, FileAccess.Read) )
{
HSSFWorkbook wb = new HSSFWorkbook(fs);
double value = wb.GetSheet("Sheet1").GetRow(1).GetCell(1).NumericCellValue;
// read other values as necessary.
}
try the following code . maybe its crude but it works
string connectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\data\\exceltest.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Sheet1$]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
SqlConnection sqlc = new SqlConnection(#"server=.\SQLEXPRESS;user id=sa;pwd=windows;database=exceltest");
sqlc.Open();
SqlCommand cmd = new SqlCommand("select * from table1", sqlc);
SqlDataAdapter sda = new SqlDataAdapter("select * from table1", sqlc);
sda.InsertCommand = new SqlCommand("insert into table1", sqlc);
DataTable dbset = new DataTable();
da.Fill(dbset);
SqlCommand cmdinsert = new SqlCommand();
cmdinsert.Connection = sqlc;
foreach (DataRow dsrc in dt.Rows)
{
string insertcommand = "insert into table1" + dbset.TableName + " ";
string cols = "";
string vals = "";
DataRow dr = dbset.NewRow();
foreach (DataColumn clm in dt.Columns)
{
dr[clm.ColumnName] = dsrc[clm.ColumnName].ToString(); ;
if (cols.Length > 0)
{
cols += ",[" + clm.ColumnName+"]";
}
else
{
cols = "["+clm.ColumnName+"]";
}
if (vals.Length > 0)
{
vals += "," + "'" + dsrc[clm.ColumnName].ToString() + "'";
}
else
{
vals = "'" + dsrc[clm.ColumnName].ToString() + "'";
}
}
insertcommand += "(" + cols + ") values("+vals+")";
cmdinsert.CommandText = insertcommand;
cmdinsert.ExecuteNonQuery();
insertcommand = "";
}
sqlc.Close();

Categories