Hitting "COM object that has been separated from its underlying RCW cannot be used" error - winforms

I am trying to write a Windows Form program on top of .NET 4.0 and accessing Microsoft Access Database. I can read and write with no problem but sometimes, I get this error:
COM object that has been separated from its underlying RCW cannot be used.
I tried to call this method (GetIDBasedonTeamName) with different inputs twice (on the same thread). The second time this is run, I got that error.
OleDbConnection conn = new OleDbConnection();
OleDbConnection mDB = new OleDbConnection();
OleDbCommand comm = new OleDbCommand();
OleDbCommand cmd;
OleDbDataReader dr;
public void OpenConnection(string name) // always call this method first in other methods to initialise connection
{
conn.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
conn.Open();
comm.Connection = conn;
comm.Parameters.Clear();
}
public string GetIDBasedonTeamName(string teamName)
{
string toReturn = "";
try
{
OpenConnection("form");
comm.CommandText = "Select ID from TeamDetails WHERE TeamName=#teamName";
comm.Parameters.AddWithValue("TeamName", teamName);
dr = comm.ExecuteReader();
while (dr.Read())
{
toReturn = dr[0].ToString();
}
}
catch (OleDbException e)
{
string err = e.Message.ToString();
return null;
}
finally
{
}
conn.Close();
dr.Close();
return toReturn;
}
Exception happened on dr = comm.ExecuteReader();.
The method that was calling this method have this 2 lines inside:
InfoConfig.team1id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam1.Text));
InfoConfig.team2id = Convert.ToInt32(dbm.GetIDBasedonTeamName(cbxTeam2.Text));
What could be the cause? I read around and they mentioned not to use different threads but it is the same thread here.
Thanks,
Guo Hong

Building on Martin Liversage's answer:
public string GetIDBasedonTeamName(string teamName) {
var connString = "Provider = Microsoft.Jet.OLEDB.4.0;Data source="
+ Application.StartupPath + "\\AppData\\" + name + ".mdb;";
using (var conn = new OleDbConnection(connString)) {
conn.Open();
using (var cmd = conn.CreateCommand()) {
cmd.CommandText="Select ID from TeamDetails WHERE TeamName = #teamName";
cmd.Parameters.AddWithValue("TeamName", teamName);
using (var rdr = cmd.ExecuteReader()) {
if (rdr.Read()) {
return (string)rdr["TeamName"];
}
//if no valid results will return null
}
}
}
}

Instead of creating the objects only once and storing them in fields in your class you should create, use and close the objects in your method. It is probably the Close you call in the end the method that releases the underlying COM objects giving you the exception on the second call.

Related

How can we use both sql and oracle database connection using one object only

I wants to fetch the data from database using C++.Net. I need to do this irrespective of db used in the system. But i don't want to change my code for each database. I am looking for a solution in C++.Net, please do help..
This is what i have now;
Oracle:
OracleConnection *myOracleConnection;
OracleDataAdapter * myDataAdapter;
DataSet * myDataSet;
myOracleConnection = new OracleConnection(S"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw;");
myOracleConnection->Open();
myDataAdapter = new OracleDataAdapter(S"select dbms_xmlgen.getxml(' select * from SampleTable') from dual ",myOracleConnection);
myDataSet = new DataSet("Sample");
Sql:
`SqlConnection *mySQLConnection;
SqlDataAdapter * myDataAdapter;
DataSet * myDataSet;
mySQLConnection = new SqlConnection(S"Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw;");
mySQLConnection->Open();
myDataAdapter = new SqlDataAdapter(S"select * from [SampleTable]",mySQLConnection);
myDataSet = new DataSet("Sample");`
i wants to do both connection using one connection object. Is there any idea to achieve this???
I can't give you c++ code, but I can help you how to do it. It will be difficult to do it in one connection, but your can get a DataSet back which will work, and you only have to do the code once.
Create a method will return a DataSet, and pass the query as well as what type of connection should be used, in this method depending on tour connection type you do your query and return your result.
You can also add a connectionstring if you wish.
Something like this (it is c# though)
DataSet GetDataSet(string sqlQuery, ConnectionType connType)
{
DataSet dataset = new DataSet("aDataSet");
using (DataTable table = dataset.Tables.Add("aDataTable"))
{
switch (connType)
{
case ConnectionType.MSSQL:
using (var conn = new SqlConnection("Data Source=(local);Initial Catalog=myDb;User Id=user;Password=pw"))
{
using (var cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
case ConnectionType.Oracle:
using (var conn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.175)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SCDB)));User Id=user;Password=pw"))
{
using (var cmd = new OracleCommand(sqlQuery, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
table.Load(reader);
}
}
}
break;
default:
break;
}
}
return dataset;
}
enum ConnectionType { MSSQL, Oracle }

Read data from SQL Server database with c#

I have list of BuilderString which I want to contain data
public List<int> IDS = new List<int>();
public List<StringBuilder> Items = new List<StringBuilder>();
What's wrong with this code?
SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True");
SqlDataReader rdr2;
SqlCommand cmd2;
con2.Open();
for (int i = 0; i < IDS.Count; i++)
{
cmd2 = new SqlCommand("select item From TransactiontData where idT=#IDS[i]", con2);
cmd2.CommandType = CommandType.Text;
rdr2 = cmd2.ExecuteReader();
SqlParameter param = new SqlParameter();
param.ParameterName = "#IDS[i]"
while (rdr2.Read())
{
Items[i].Append((StringBuilder)rdr2["item"]);
}
}
You need to rearrange your code a bit:
using (SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True"))
using (SqlCommand cmd2 = new SqlCommand("select item From TransactiontData where idT = #IDS", con2))
{
// add the paramter to the command
cmd2.Parameter.Add("#IDS", SqlDbType.Int);
con2.Open();
for (int i = 0; i < IDS.Count; i++)
{
// set the parameter value
cmd2.Parameter["#IDS"].Value = IDS[i];
// only *THEN* call ExecuteReader()
using (SqlDataReader rdr2 = cmd2.ExecuteReader())
{
while (rdr2.Read())
{
// **NOT SURE** what you're trying to do here.....
// First of all, you need to just call Items.Add()
// to add new items to the list - and I'm TOTALLY
// UNCLEAR what you're trying to do casting the reader
// value to a StringBuilder.......
//
// Items[i].Append((StringBuilder)rdr2["item"]);
//
// replaced with what *might* make more sense.....
Items.Add(rdr2["item"].ToString());
}
rdr.Close();
}
}
con2.Close();
}
Points to note:
I would recommend to always put your SqlConnection, SqlCommand and SqlDataReader into using() {...} blocks to ensure proper disposal
you need to add your parameter and set its value BEFORE you call .ExecuteReader()!
Since the query itself never changes - there's no point in creating a new SqlCommand on every iteration. Create the command once - and then just set the parameter value (which is the only thing changing) once per iteration
You need to assign the parameter value in the application code rather than within the query. I'm not sure exactly what you are trying to accomplish by casting the column value as a StringBuilder. Assuming that each StringBuilder item is to contain a single string retrieved from a varchar/nvarchar column, the example below will do that.
for (int i = 0; i < IDS.Count; i++)
{
var cmd2 = new SqlCommand("select item From TransactiontData where idT=#IDS", con2);
SqlParameter param = new SqlParameter("#IDS", SqlDbType.Int) { Value = IDS[i] };
var rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
Items.Add(new StringBuilder((string)rdr2["item"]));
}
}

System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'

I have been trying to debug a piece of code and I have been thus far very unsuccessful in doing this.
I keep on getting this error
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near ')'
and I can't seem to see where the error is.
The code is below, having looked at various answers on this site and looked at the examples. The situation is that I am writing a program that accesses a database and is able to add and save data to that database. It is located on a server - though this is on my laptop.
I have written, re-written and copied the connection string to ensure there are no mistakes in it and even dropped a copy of the string into word and compared it to the one that is in the coding itself but to no avail.
public partial class AddingClients : Form
{
public AddingClients()
{
InitializeComponent();
}
String CompanyName2;
String ClientName2;
String CompanyAddress12;
String CompanyAddress22;
String CompanyAddress32;
String CompanyTown2;
String CompanyPostCode2;
String TelephoneNumber2;
String CompanyEMail2;
String CompanyNotes2;
String ClientReference2;
public SqlConnection con;
public void connection()
{
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
}
private void Finish_Click(object sender, EventArgs e)
{
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
//this method moves to the next screen.
this.Hide();
Asset M1 = new Asset();
M1.Show();
}
private void SaveandNext_Click(object sender, EventArgs e){
ClientReference2 = Id.Text;
CompanyName2 = CompanyName.Text;
ClientName2 = ClientName.Text;
CompanyAddress12 = CompanyAddress1.Text;
CompanyAddress22 = CompanyAddress2.Text;
CompanyAddress32 = CompanyAddress3.Text;
CompanyTown2 = CompanyTown.Text;
CompanyPostCode2 = CompanyPostCode.Text;
TelephoneNumber2 = TelephoneNumber.Text;
CompanyEMail2 = CompanyEMail.Text;
CompanyNotes2 = CompanyNotes.Text;
String connectionstr = #"Data Source=ACER\PATTESTSERVER;Initial Catalog=PatTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;";
con = new SqlConnection(connectionstr);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail, CompanyNotes,) VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10, #parameter11,)", con);
cmd.Parameters.AddWithValue("#parameter1", ClientReference2);
cmd.Parameters.AddWithValue("#parameter2", ClientName2);
cmd.Parameters.AddWithValue("#parameter3", CompanyName2);
cmd.Parameters.AddWithValue("#parameter4", CompanyAddress12);
cmd.Parameters.AddWithValue("#parameter5", CompanyAddress22);
cmd.Parameters.AddWithValue("#parameter6", CompanyAddress32);
cmd.Parameters.AddWithValue("#parameter7", CompanyTown2);
cmd.Parameters.AddWithValue("#parameter8", CompanyPostCode2);
cmd.Parameters.AddWithValue("#parameter9", TelephoneNumber2);
cmd.Parameters.AddWithValue("#parameter10", CompanyEMail2);
cmd.Parameters.AddWithValue("#parameter11", CompanyNotes2);
cmd.ExecuteNonQuery();
this.Hide();
AddingClients M1 = new AddingClients();
M1.Show();//Saves the current data then goes to the next record to be tested.
You have an extra comma before the closing ) in your column list and VALUES sections:
SqlCommand cmd = new SqlCommand("INSERT INTO ClientTable(Id, ClientName, CompanyName, CompanyAddress1, CompanyAddress2, CompanyAddress3, CompanyTown, CompanyPostCode, TelephoneNumber, CompanyEMail,
CompanyNotes,)
****
VALUES(#parameter1, #parameter2, #parameter3, #parameter4, #parameter5, #parameter6, #parameter7, #parameter8, #parameter9, #parameter10,
#parameter11,)", con);
****
Remove that and you should be fine

Stored Procedure returns a temporary table that I need to convert to a CSV file

I basically have a stored procedure that I call through a method:
Time_Tracker.BLL.ResultsManager.GetCSV(Convert.ToDateTime("2014-01-11"));
It returns 8 columns of data ranging from 25 to 150 records.
I need to be able to convert it to a CSV file to a path of the users choosing. I am able to get it into my code behind as an array ( Results[] TEST = new Results[25]; ) and have verified that the data is O.K. I see plenty of posts were they use a DataTable as a source to convert to CSV, but I am not sure how to load a DataTable from the method that calls the stored procedure. Same thing with DataGridView, not sure how to load the data into a DataGridView either.
I have also seen methods were they use SqlDataAdapter to populate a DataTable. Since I use methods to that work directly with stored procedures, I don't want to have to use SqlDataAdapter and provide the database configuration info each time.
IF someone could help me load it into a DataTable or DataGridView, I think I can figure it out from there.
Thank you in advance.
Eric
Just define a data table and use the load command to move the data from the reader to the data table.
http://msdn.microsoft.com/en-us/library/d7125bke.aspx
This is right from MSDN. I added two lines to load a data table.
-- Code from msdn
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
SqlDataReader reader = cmd.ExecuteReader();
-- This is my addition
DataTable dt = new DataTable();
dt.Load(reader);
sqlConnection1.Close();
I still do not understand what you are trying to do. You can create a data table, xml record set, via coding.
The code below can be used to translate an array to a DataTable. Some work is needed on your side to add your details.
http://msdn.microsoft.com/en-us/library/skef0k7a(v=vs.110).aspx
// Create sample Customers table.
DataTable table = new DataTable();
table.TableName = "Customers";
// Create two columns, ID and Name.
DataColumn idColumn = table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
// Set the ID column as the primary key column.
table.PrimaryKey = new DataColumn[] { idColumn };
table.Rows.Add(new object[] { 0, "Mary" });
table.Rows.Add(new object[] { 1, "Andy" });
table.Rows.Add(new object[] { 2, "Peter" });
table.AcceptChanges();
return table;
I hope this helps. If not, I still do not get the business requirement.
I figured it out (See Below). I will mark this as solved and once again, Thank You for your help !
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
if (dr[i] is DateTime)
{
if (((DateTime)dr[i]).TimeOfDay.TotalSeconds == 0) // Time Since Midnight (in Seconds)
{
sw.Write(((DateTime)dr[i]).ToString("yyyy-MM-dd"));
}
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < iColCount - 1) sw.Write(",");
}
sw.Write(sw.NewLine);
}
Here is what I ended up doing for anyone else looking for help:
protected void btnCSV_Click(object sender, EventArgs e)
{
try
{
// HATE EXPOSING THE DATABASE CONNECTION THIS WAY !!!
SqlConnection sqlConnection1 = new SqlConnection(DAL.DBUtils.SqlConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "[dbo].[usp.CSV_OUT]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateBeg", Time_Tracker.Utilities.TimeCard_Start_Date());
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
sqlConnection1.Close();
ExportToCSV(dt, ConfigurationManager.AppSettings["CSVPath"].ToString(), "CSV_Hours_Data_" + Time_Tracker.Utilities.TimeCard_Start_Date().AddDays(+6).ToString("MM_dd_yyyy") + ".csv");
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}
public static void ExportToCSV(DataTable dt, string strFilePath, string fileName)
{
try
{
var sw = new StreamWriter(strFilePath + fileName, false);
// Write the headers.
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1) sw.Write(",");
}
sw.Write(sw.NewLine);
// Write rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string output = dr[i].ToString();
if (dr[i] is DateTime)
{
if (((DateTime)dr[i]).TimeOfDay.TotalSeconds == 0) // Time Since Midnight (in Seconds)
{
output = (((DateTime)dr[i]).ToString("yyyy-MM-dd"));
}
}
if (output.Contains(";") || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
if (Regex.IsMatch(output, #"(?:\r\n|\n|\r)"))
output = string.Join(" ", Regex.Split(output, #"(?:\r\n|\n|\r)"));
sw.Write(output);
}
if (i < iColCount - 1) sw.Write(",");
}
sw.Write(sw.NewLine);
}
sw.Close();
// Causes Save As Dialog box to appear for user.
String FileName = fileName;
String FilePath = strFilePath;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.Flush();
response.End();
}
catch (Exception ex)
{
Utilities.ErrorLog(ex.Message, ex.GetType().ToString(), ex.StackTrace, #"Time_Tracker.txt");
}
}

Uploading excel in to SQL Server in ASP.NET

When I try to upload an Excel sheet of data into SQL Server I get the following error first time it uploads well when I try to upload it shows the following error
Before uploading I am deleting files in the directory
string[] filePaths1 = Directory.GetFiles(Server.MapPath(#"Excel\"));
foreach (string filePath1 in filePaths)
File.Delete(filePath1);
The process cannot access the file
'C:\inetpub\vhosts\xyz.com\httpdocs\newofficework\Excel\super.xlsx'
because it is being used by another process.
You seem to be performing multiple actions here (1) Delete and then (2) Upload
How are you Uploading the files? If you are using the SaveAs method, then please ensure that you Dispose the same.
E.g. (fuExcel is my FileUpload control)
fuExcel.SaveAs(sUniqueFilePath); // string variable containing file path
fuExcel.Dispose();
The Page having a FileUpload control and the Upload button, on selecting the Excel file user needs to click on Upload button to store the data to Server. Here we are treating the uploaded file as database hence we need to create OLEDB connection to this file, from this connection will be created and the data is fetched to C# as DataTable. '[Sheet1$]' is the Name of the Worksheet where requires data is present.
string SourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(SourceConstr);
string query = "Select * from [Sheet1$]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);
From this code connection will be created for the Excel file and the data in Sheet1 will be dumped to the dtExcel of type DataTable.
Note:'$' must be there after the worksheet name.
fileName = FileUpload1.ResolveClientUrl(FileUpload1.PostedFile.FileName);
int count = 0;
DataClassesDataContext conLinq = new DataClassesDataContext("Data Source=server name;Initial Catalog=Database Name;Integrated Security=true");
try
{
DataTable dtExcel = new DataTable();
string SourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + fileName + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection con = new OleDbConnection(SourceConstr);
string query = "Select * from [Sheet1$]";
OleDbDataAdapter data = new OleDbDataAdapter(query, con);
data.Fill(dtExcel);
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
try
{
count += conLinq.ExecuteCommand("insert into table name values(" + dtExcel.Rows[i][0] + "," + dtExcel.Rows[i][1] + ",'" + dtExcel.Rows[i][2] + "',"+dtExcel.Rows[i][3]+")");
}
catch (Exception ex)
{
continue;
}
}
if (count == dtExcel.Rows.Count)
{
<--Success Message-->
}
else
{
<--Failure Message-->
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
conLinq.Dispose();
}
Add these two name space in your class file
using System.Data.OleDb;
using System.Data.SqlClient;
Use following code
public void importDataFromExcel(string excelFilePath)
{
//Declare Variables - Edit these based on your particular situation
string sSQLTable = "tDataMigrationTable";
// make sure your sheet name is correct, here sheet name is Sheet1, so you can change your sheet name if have different
string myExcelDataQuery = "Select StudentName,RollNo,Course from [Sheet1$]";
try
{
//Create our connection strings
string sExcelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilePath + ";Extended Properties=" + "\"Excel 8.0;HDR=YES;\"";
string sSqlConnectionString = "SERVER=MyDatabaseServerName;USER ID=DBUserId;PASSWORD=DBUserPassword;DATABASE=DatabaseName;CONNECTION RESET=FALSE";
//Execute a query to erase any previous data from our destination table
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
//Series of commands to bulk copy data from the excel file into our SQL table
OleDbConnection OleDbConn = new OleDbConnection(sExcelConnectionString);
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
}
catch (Exception ex)
{
//handle exception
}
}

Resources