SqlBulkCopy ColumnMappings not working [duplicate] - c#

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Unable to compare the columns in SqlBulkCopy
I have an excel sheet with columns :
excelid | exceldata
1 | cat
2 | bat
3 | rat
My database table:
id (int) | varchar(50)
following is my code:
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");
//string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=ARBAAZ-1B14C081;Initial Catalog=abc;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch { }
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "data");
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable"; r = "";
SqlCommand cmd = new SqlCommand(s, con);
try { SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch { }
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString(); Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
}
//protected void Button2_Click(object sender, EventArgs e)
//{
// string fileName = FileUpload1.PostedFile.FileName.ToString();
// Response.Write(fileName);
//}
protected void Button2_Click(object sender, EventArgs e)
{
}

Your excel spreadsheet columns are:
excelid | exceldata
Your db columns are (i'm guessing as you don't actually say):
id | data
Therefore your mappings should be
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("excelid", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("exceldata", "data");

Related

How do I connect a MS Access database with a password and a .mdb , accdb database

I want to connect different access database (they have same tables, same columns) to my system to make a report and this database has a password. I use a openfileDialog to take this database from my files and I want to connect both .mdb, .accdb but but when I use Microsoft.jet.oledb.12.0, I get an error
The microsoft.jet.olebd.12.0 provider is not registered on local machine
This is my code:
private void tileBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open file Dialog";
fdlg.InitialDirectory = #"C:\Desktop";
fdlg.Filter = "(*.mdb)|*.mdb|(*.accdb)|*accdb";
//fdlg.Filter = "All Files (*.*)|*.mdb|*.accdb" + "MS-Access Database Files (*.accdb)|*.accdb, (*.mdb)|*.mdb";
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = fdlg.FileName;
}
}
private void txtRead_Click(object sender, EventArgs e)
{
//connection string
String strDSN = "Provider=Microsoft.Jet.OLEDB.12.0;" + "Data Source=" + txtFilePath.Text;
try
{
//Create a connection and open it
OleDbConnection conn = new OleDbConnection(strDSN);
conn.Open();
String strSQl = "SELECT * FROM Student;";
//create data adapter
OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQl, conn);
// Create and fill dataset
DataSet dtSet = new DataSet();
myCmd.Fill(dtSet);
DataTable dt = dtSet.Tables[0];
dataGridView1.DataSource = dtSet.Tables[0];
//add items to the list box
listBox1.Items.Add("ID,F_Name,S_Name," + "Age");
listBox1.Items.Add("=====================================");
foreach (DataColumn dc in dt.Columns)
{
listBox1.Items.Add(dc.ColumnName + "," + dc.DataType + "," + dc.Unique + "," + dc.AutoIncrement + "," + dc.AllowDBNull);
}
OleDbCommand cmd = new OleDbCommand("SELECT student.ID, student.F_name, student.S_name, student.Age, Teachers_Info.Teachers_ID, Teachers_Info.Firstname, Teachers_Info.Surname, Teachers_Info.Teachers_Subject, Teachers_Info.Teachers_code FROM student, Teachers_Info ORDER BY student.ID;", conn);
OleDbDataReader Reader = cmd.ExecuteReader();
//if (Reader.HasRows)
if (Reader.HasRows)
{
Reader.Read();
txtID.Text = (Reader["ID"].ToString());
txtF_name.Text = (Reader["F_name"].ToString());
txtS_name.Text = (Reader["S_name"].ToString());
txtAge.Text = (Reader["Age"].ToString());
txtTeachers_ID.Text = (Reader["Teachers_ID"].ToString());
txtFirstname.Text = (Reader["Firstname"].ToString());
txtSurname.Text = (Reader["Surname"].ToString());
txtTeachers_Subject.Text = (Reader["Teachers_Subject"].ToString());
txtTeachers_code.Text = (Reader["Teachers_code"].ToString());
}
//close connection
conn.Close();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message.ToString());
}
}

Unable to import excel to DB table in server

I am using the below code to import excel data into DB table. The code works fine in my local and when I move this code to server the import fails in between. Also I don't get any error messages and I get a message data saved successfully.
For Ex: The excel has 75,000 data's and only 13,500 records are getting inserted and the size of the excel file is 5 MB.
Any suggestions about the possible problems?
CS:
protected void btnImportData_Click(object sender, EventArgs e)
{
try
{
string strCS = string.Empty; ;
string strFileType = Path.GetExtension(FileUploadExcel.FileName).ToLower();
string query = "";
lblError.Text = "";
string FileName = string.Empty;
FileName = Path.GetFileName(FileUploadExcel.PostedFile.FileName);
string Extension = Path.GetExtension(FileUploadExcel.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
string path = Path.GetFileName(Server.MapPath(FileUploadExcel.FileName));
System.IO.File.Delete(Server.MapPath(FolderPath) + path);
FileUploadExcel.SaveAs(Server.MapPath(FolderPath) + path);
string filePath = Server.MapPath(FolderPath) + path;
if (strFileType != String.Empty)
{
if (strFileType.Trim() == ".xls")
{
strCS = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
strCS = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please upload the correct file format')", true);
return;
}
try
{
OleDbConnection conn = new OleDbConnection(strCS);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname = dt.Rows[0]["Table_Name"].ToString();
query = "SELECT * FROM [" + sheetname + "]";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn = null;
}
string strSqlTable = "TABLENAME";
string sclearsql = "delete from " + strSqlTable;
SqlConnection sqlconn = new SqlConnection(strCon);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(strCS);
oledbconn.Open();
OleDbCommand oledbcmd = new OleDbCommand(query, oledbconn);
oledbcmd.CommandTimeout = 120;
OleDbDataReader dReader = oledbcmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(strCon);
bulkCopy.DestinationTableName = strSqlTable;
bulkCopy.BulkCopyTimeout = 120;
bulkCopy.BatchSize = 1000;
bulkCopy.WriteToServer(dReader);
oledbconn.Close();
ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Data saved successfully');window.location='Panel.aspx';", true);
}
catch (Exception ex)
{
lblError.Text = "Upload status: The file could not be uploaded due to following reasons.Please check: " + ex.Message;
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a file to import the data.')", true);
}
}
catch (Exception ex)
{
lblError.Text = "Upload status: The file could not be uploaded due to following reasons.Please check: " + ex.Message;
}
}
Hi remove the data reader on you code which read the excel file twice and use the dataset to fill out your SQL table:
See below:
DataTable dtexcel = new DataTable();
using (OleDbConnection conn = new OleDbConnection(strCS))
{
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//Looping a first Sheet of Xl File
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_"))
{
string query = "SELECT * FROM [" + sheet + "]";
OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
dtexcel.Locale = CultureInfo.CurrentCulture;
daexcel.Fill(dtexcel);
}
}
using (SqlConnection sqlconn = new SqlConnection(strCon))
{
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
}
using (SqlConnection sqlconn = new SqlConnection(strCon))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlconn))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = strSqlTable;
sqlconn.Open();
sqlBulkCopy.WriteToServer(dtexcel);
}
}
Have you tried using the dts wizard? it is a nice tool if you have a excel sheet with data.
you use it by opening the command prompt. windowsbutton + r, and the write cmd.
and from in here you write dtswizard
then a wizard opens in a new window where you can select the excel sheet that you want to insert. There is many tutorials on google.
Hope you can use this

How to display certain table schema columns in a datagridview control using C#?

I have a method that displays the entire schema of an MS Access table into a datagridview control. How would I be able to display just the column name and data type schema columns in the datagridview. The method that I am working with is below. Thank you for any advice.
private void ButtonFieldHelp_Click(object sender, EventArgs e)
{
char ch = '"';
dbConn = new OleDbConnection();
dbCmd = new OleDbCommand();
DataTable data;
OleDbDataReader reader;
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + this.stringData + ch;
dbConn.Open();
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT * FROM " + this.comboBox.SelectedItem.ToString();
reader = dbCmd.ExecuteReader();
foreach (DataRow tableField in data.Rows)
{
foreach (DataColumn tableProperty in data.Columns)
{
dataGridView.DataSource = data;
}
}
this.txtRecords.Text = data.Rows.Count.ToString();
reader.Close();
dbConn.Close();
}
Here is your code modified to work as you need using OleDbDataAdapter:
private void ButtonFieldHelp_Click(object sender, EventArgs e)
{
char ch = '"';
var dbConn = new OleDbConnection();
var dbCmd = new OleDbCommand();
DataTable data = new DataTable();
OleDbDataReader reader;
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + this.stringData + ch;
dbConn.Open();
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT * FROM " + this.comboBox.SelectedItem.ToString();
//reader = dbCmd.ExecuteReader();
OleDbDataAdapter adapter = new OleDbDataAdapter(dbCmd);
adapter.Fill(data);
var dataTable = new DataTable();
dataTable.Columns.Add("ColumnName");
dataTable.Columns.Add("ColumnType");
foreach (DataColumn column in data.Columns)
{
dataTable.Rows.Add(column.ColumnName, column.DataType.ToString());
}
this.dataGridView1.DataSource = dataTable;
this.txtRecords.Text = data.Rows.Count.ToString();
dbConn.Close();
}

Getting next row of table of access database every time on clicking a button

I am trying to get next rows from the table of access database but I am getting last row all time.
Please guide me how to loop through all rows?
Here is the code:
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; DataSource=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
while(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
con1.Close();
}
=It`s must outside a button click:
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
int i = 2;
con1.Close();
Its must inside button click. You must make i property of form
if(i<=count)
{
string cmdstr = "select * from table where id = " + i;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
i++;
}
But i think it`s may rewrite to more beauty solve.
Sounds like you are after something like
private int _currentRecordId = -1;
...
string cmdStr = String.Format("SELECT * FROM Table WHERE id > {0} ORDER BY id LIMIT 1", _currentRecordId);
using (var con = new OleDbConnection(constr))
using (var com = new OleDbCommand(cmdStr, con))
{
con.Open();
using(var reader = com.ExecuteReader())
{
while (reader.Read())
{
_currentRecordId = reader.GetInt32(0); // whatever field the id column is
// populate fields
}
}
}
On first call this will retrieve the first record with an ID > -1. It then records whatever the ID is for this record so then on the next call it will take the first record greater than that e.g. if the first record is id 0 then the next record it will find is 1 and so on...
This only really works if you have sequential IDs of course.
Assuming that your table is not big (meaning it contains a manegeable number of records) you could try to load everything at the opening of your form and store that data in a datatable.
At this point the logic in your button should simply advance the pointer to the record to be displayed.
private DataTable data = null;
private int currentRecord = 0;
protected void form_load(object sender, EventArgs e)
{
using(OleDbConnection con1 = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("select * from table", con1))
{
con1.Open();
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
data = new DataTable();
da.Fill(data);
}
DisplayCurrentRecord();
}
}
private void DisplayCurrentRecord()
{
label1.Text = String.Format("{0}", data.Rows[currentRecord][1]);
RadioButton1.Text = String.Format("{0}", data.Rows[currentRecord][2]);
RadioButton2.Text = String.Format("{0}", data.Rows[currentRecord][3]);
RadioButton3.Text = String.Format("{0}", data.Rows[currentRecord][4]);
RadioButton4.Text = String.Format("{0}", data.Rows[currentRecord][5]);
}
protected void btn_clk(object sender, EventArgs e)
{
if(currentRecord >= data.Rows.Count - 1)
currentRecord = 0;
else
currentRecord++;
DisplayCurrentRecord();
}
Keep in mind that this is just an example. Robust checking should be applied to the rows (if they contains null values) and if there are rows at all in the returned table. Also, this is a poor man approach to the problem of DataBindings in WinForm, so perhaps you should look at some tutorials on this subject
Hope your table is not really named Table, that word is a reserved keyword for Access
simply remove the for loop to fetch record one by one
int lastFetchedRecordIndex=2;
protected void btn_clk(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Documents\databaseb.mdb";
string cmdstr1 = "select count(*) from table";
OleDbConnection con1 = new OleDbConnection(constr);
OleDbCommand com1 = new OleDbCommand(cmdstr1, con1);
con1.Open();
int count = (int) com1.ExecuteScalar();
string cmdstr = "select * from table where id = " + lastFetchedRecordIndex;
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
label1.Text = String.Format("{0}", reader[1]);
RadioButton1.Text = String.Format("{0}", reader[2]);
RadioButton2.Text = String.Format("{0}", reader[3]);
RadioButton3.Text = String.Format("{0}", reader[4]);
RadioButton4.Text = String.Format("{0}", reader[5]);
con.Close();
lastFetchedRecordIndex++;
con1.Close();
}

How to upload table data from Excel to SQL Server 2008 in C# ASP.Net

protected void btnup_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (System.IO.Path.GetExtension(FileUpload1.FileName) == ".xls" || System.IO.Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
FileUpload1.SaveAs(Server.MapPath("~/Excal/sample.xlsx"));
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
string sSourceConstr = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\sample.xlsx; Extended Properties=""Excel 12.0;HDR=YES;""";
string sDestConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
string sql = string.Format("Select [ID],[Name],[Designation] FROM [{0}]", "sample$");
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sDestConstr))
{
bulkCopy.DestinationTableName = "rr";
//You can mannualy set the column mapping by the following way.
//bulkCopy.ColumnMappings.Add("MSISDN", "MSISDN");
bulkCopy.WriteToServer(dr);
}
}
}
lblmsg.Text = "Record update";
}
I have done that before few day. Below code works for me ..
try
{
string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Path of File + ";" +
#"Extended Properties=""Excel 12.0 Xml;HDR=Yes""";
//Create Connection to Excel work book
OleDbConnection excelConnection =
new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand
("Select * from [Sheet1$]",
excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "ExcelTable"; // write your table name
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Categories

Resources