create new DataBase & fill with another DataBase - c#

I have a Problem in C# windows program that is I can't work with 2 database those are
simple database in tables and Data. in this Project I want to open Access DataBase and Create New Access DataBase with another Name But with Same Tables And Columns And Rows and fill with Source Data that is in Source Database.
I can't read from source DB and insert into new destination DataBase. the sorce code is below please Help me to Complete this Project, thanks a lot.
private void button3_Click(object sender, EventArgs e)
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = #"provider=Microsoft.ACE.OLEDB.12.0;" + #"data source=" + openFileDialog1.FileName;
OleDbCommand cmd = new OleDbCommand();
cn.Open();
DataTable table = cn.GetSchema("Tables");
int i = 0;
foreach (System.Data.DataRow row in table.Rows)
{
if ((string)row["TABLE_TYPE"] == "TABLE")
{
comboBox1.Items.Add(row["TABLE_NAME"]);
Tables[i] = row["TABLE_NAME"].ToString();
listBox1.Items.Add(Tables[i]);
i++;
n++;
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection conne = new OleDbConnection();
conne.ConnectionString = #"provider=Microsoft.ACE.OLEDB.12.0;" + #"data source=" + openFileDialog1.FileName;
conne.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conne;
DataTable Dt = new DataTable();
cmd.CommandText = "select * from " + comboBox1.Text;
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(Dt);
dataGridView1.DataSource = Dt;
dataGridView1.Visible = true;
conne.Close();
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "accdb|*.accdb";
saveFileDialog1.Title = "Save Access DataBase File";
saveFileDialog1.FileName = strFileName;
saveFileDialog1.ShowDialog();
System.IO.File.Copy(openFileDialog1.FileName, saveFileDialog1.FileName);
ADOX.Catalog cat = new ADOX.Catalog();
cat.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + saveFileDialog1.FileName);
Console.WriteLine("Database Created Successfully");
OleDbConnection connsave = new OleDbConnection();
connsave.ConnectionString = #"provider=Microsoft.ACE.OLEDB.12.0;" + #"data source=" + saveFileDialog1.FileName;
connsave.Open();
OleDbCommand cmdsave = new OleDbCommand();
cmdsave.Connection = connsave;
OleDbConnection connopen = new OleDbConnection();
connopen.ConnectionString = #"provider=Microsoft.ACE.OLEDB.12.0;" + #"data source=" + openFileDialog1.FileName;
connopen.Open();
OleDbCommand cmdopen = new OleDbCommand();
cmdopen.Connection = connopen;
int i = 0;
foreach (string strtablename in Tables)
{
if (i < n)
{
cmdsave.CommandText = "CREATE TABLE [" + Tables[i] + "]";
cmdsave.ExecuteNonQuery();
cmdsave.CommandText = "DELETE FROM [" + Tables[i] + "]";
cmdsave.ExecuteNonQuery();
cmdopen.CommandText = "SELECT * FROM [" + Tables[i] + "]";
cmdopen.ExecuteNonQuery();
cmdsave.CommandText = "INSErT INTO [" + Tables[i] + "]";
cmdsave.ExecuteNonQuery();
i++;
}
}
connopen.Close();
connsave.Close();
textBox2.Text = saveFileDialog1.FileName.ToString();
MessageBox.Show("DataBase Save Sucessfull in \"" + textBox2.Text + "\"");
}

You could execute an INSERT INTO statement using the IN clause:
INSERT INTO DestinationTable (DestinationField)
IN '' [;DATABASE= C:\Users\Rob\Documents\Northwind 2007.accdb]
SELECT SourceField FROM SourceTable
They go into more detail here:
http://blogs.office.com/b/microsoft-access/archive/2009/03/27/accessing-external-data-using-the-in-clause.aspx

Related

prevent duplicate data from Excel to db via Oledb c#

I Have a excel and I want Upload only four columns of that to SQL Table with a button.
The problem is when I repeat click the button all of that data will be duplicated but I Don't want that. I want only new data to be update.
My query:
protected void Button1_Click(object sender, EventArgs e)
{
int UserID;
int InsuID;
string Result;
int Year;
//** مسیر فایل اکسل**
String ExcelPath = #"D:\Insu_lab.xlsx";
//** کانکشن به آفیس**
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
UserID = Convert.ToInt32(dr[0].ToString());
InsuID = Convert.ToInt32(dr[1].ToString());
Result = dr[2].ToString();
Year = Convert.ToInt32(dr[3].ToString());
savedata(UserID, InsuID, Result, Year);
Label1.Text = "اطلاعات با موفقیت در دیتابیس ذخیره شد";
}
}
private void savedata(int UserID, int InsuID, string Result, int Year)
{
String query = "insert into tbl_Result(UserID,InsuID,Result,Year) values(" + UserID + ",'" + InsuID + "','" + Result + "','" + Year + "') ";
String mycon = "Data Source=MC6082; Initial Catalog=Insurance; Integrated Security=true";
SqlConnection con = new SqlConnection(mycon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
Solution 1: When you clickedon button, that(button) disable the button.
Button1.disable = true;
When export ended:
Button1.disable = false;
Solution 2: you can use from jquery ajax in this part.

Database dropdown list value printed on labels

I'm using ASP.net to make a dropdown menu. The dropdown menu is linked to a database, all that works. If a value is selected in the dropdown, labels have to be filled that match the dropdown value in the database.
Hope I'm being clear, here's what I have so far :
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.Open();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
OleDbCommand cmd1 = new OleDbCommand("Select (Prijs, Jaartal, ISBN) from JipEnJanneke where Titel = #Titel", conn);
cmd1.Parameters.AddWithValue("#Titel", DropDownList1.SelectedValue.ToString());
OleDbDataReader rd = cmd1.ExecuteReader();
while (rd.Read())
{
lbl_Prijs.Text = rd["Prijs"].ToString();
lbl_Jaar.Text = rd["Jaartal"].ToString();
lbl_Isbn.Text = rd["ISBN"].ToString();
}
conn.Close();
Unfortunately this leaves the labels empty. If I add the function to my page_load the labels do get filled, but for some reason only by the first value in the dropdown. A similair post on here suggested shoving it in the selectindexchanged, but that leaves it empty for me. Anyone got an idea?
Here's my page_load event right now
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
//conn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
lblConnectionFeedback.Text = "";
try
{
conn.Open();
lblConnectionFeedback.Text += "Connection is: " + conn.State.ToString();
// HIER QUERY
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Boeken";
OleDbDataReader rd = cmd.ExecuteReader();
DropDownList1.DataSource = rd;
DropDownList1.DataTextField = "Titel";
DropDownList1.DataValueField = "Titel";
DropDownList1.DataBind();
rd.Close();
conn.Close();
}
catch (Exception exc)
{
lblConnectionFeedback.Text = exc.Message;
}
finally
{
conn.Close();
lblConnectionFeedback.Text += "<br />Connection is: " + conn.State.ToString();
}
In your load event AND your code in the dropdown_selectedindexchanged, check the IsPostBack of the page. Ex :
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack){
OleDbConnection conn = new OleDbConnection();
conn.Open();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
OleDbCommand cmd1 = new OleDbCommand("Select (Prijs, Jaartal, ISBN) from JipEnJanneke where Titel = #Titel", conn);
cmd1.Parameters.AddWithValue("#Titel", DropDownList1.SelectedValue.ToString());
OleDbDataReader rd = cmd1.ExecuteReader();
while (rd.Read())
{
lbl_Prijs.Text = rd["Prijs"].ToString();
lbl_Jaar.Text = rd["Jaartal"].ToString();
lbl_Isbn.Text = rd["ISBN"].ToString();
}
conn.Close();
}
}
Load :
if (!IsPostBack){
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
//conn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\JipEnJanneke.mdb";
lblConnectionFeedback.Text = "";
try
{
conn.Open();
lblConnectionFeedback.Text += "Connection is: " + conn.State.ToString();
// HIER QUERY
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM Boeken";
OleDbDataReader rd = cmd.ExecuteReader();
DropDownList1.DataSource = rd;
DropDownList1.DataTextField = "Titel";
DropDownList1.DataValueField = "Titel";
DropDownList1.DataBind();
rd.Close();
conn.Close();
}
catch (Exception exc)
{
lblConnectionFeedback.Text = exc.Message;
}
finally
{
conn.Close();
lblConnectionFeedback.Text += "<br />Connection is: " + conn.State.ToString();
}
}
Please check that the AutoPostBack property of the DropDownList1 is set to True.

Error with SqlBulkCopyColumnMapping

I am able to import excel sheet data into sql server table but i am unable to implement column mapping. please help.
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=DITSEC3;Initial Catalog=test;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";
bulkCopy.WriteToServer(dr);
con.Open();
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("id", "ida");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("data", "dataa");
con.Close();
}
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 !";
}
}
}
Error:
No value given for one or more required parameters.
You created but didn't add the mappings to SqlBulkCopy.
Add the code below:
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);

how to import multiple excel sheets into 2 sql server tables?

Am having one excel file with 2 different worksheets as fundmodelrate and project.Now I want to import these 2 different sheet values into 2 different sql tables(k2_fundmodelrate,k2_project).I can able to do import only if am working with 1 sheet and and 1 table,but I want two sheets values to be imported on two tables at the same time on button click event.
My code below:
private String strConnection = "Data Source=kuws4;Initial Catalog=jes;User ID=sa;Password=******";
protected void btnSend_Click(object sender, EventArgs e)
{
string path = fileuploadExcel.PostedFile.FileName;
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\fmr.xls;Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select * from [FundModelRate$]", excelConnection);
//OleDbCommand cmd1 = new OleDbCommand("Select * from [FundModelRate$], [Project$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "K2_FundModelRate";
// sqlBulk.DestinationTableName = "K2_Project";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
I think the only way is to loop through your two sheets.
Have a look at This post. This will help you get the sheet names.
When you have the sheet names, you can then just loop through them and then load them into SQL.
Maybe this can help you:
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
string excelConnection = "";
if(strFile.Trim().EndsWith(".xlsx"))
{
excelConnection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if(strFile.Trim().EndsWith(".xls"))
{
excelConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
objConn = new OleDbConnection(excelConnection);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
for(int j=0; j < excelSheets.Length; j++)
{
OleDbCommand cmd = new OleDbCommand("Select * from " + excelSheets[j], excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "YourDestinationTableName";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
Note: Not tested
public void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "test_data";//sql table name
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if havedifferent
string myexceldataquery = "select * 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=ServerName;user id=sa;password=sa;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);
DataTable dt = new DataTable();
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
oledbconn.Close();
}
catch (Exception)
{
throw;
}
}
/*---------- call that file on buttonclick through OpenDialogBox--------*/
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
string strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
importdatafromexcel(strfilename);
}
Console.WriteLine(result);
MessageBox.Show("Exported to SQL successfully");
}

Comparing values in Data Table in c#

I have loaded Two Excel files in two datable now i have to check that the Specific value of column one of DataTable1 exist in specific cloumn of DataTable 2 or not. I have only one output in rich Text Box which is wrong . What should i do
string connectionStringold = Application.StartupPath + "\Language-Resources-3.0" + ".xls";
string connstrold = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + connectionStringold + ";Extended Properties=Excel 8.0";
OleDbConnection connold = new OleDbConnection(connstrold);
string strSQLold = "SELECT * FROM [Resources$]";
OleDbCommand cmdold = new OleDbCommand(strSQLold, connold);
OleDbDataAdapter daold = new OleDbDataAdapter(cmdold);
DataTable dtold = new DataTable();
daold.Fill(dtold);
// dataGridView1.DataSource = dtold;
string connectionString = Application.StartupPath + "\\x_Lang_Res" + ".xls";
string connstr = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + connectionString + ";Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(connstr);
string strSQL = "SELECT * FROM [Chinese$]";
OleDbCommand cmd = new OleDbCommand(strSQL, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
// dataGridView1.DataSource = dt;
foreach (DataRow row in dt.Rows)
{
string aa = row[1].ToString();
foreach (DataRow rowold in dtold.Rows)
{
string old = rowold[3].ToString();
if (!rowold[3].ToString().Contains(aa))
{
richTextBox1.Text = aa + "\n\r";
}
}
}
You are setting the result to the RTB.Text property each time.
if (!rowold[3].ToString().Contains(aa))
{
richTextBox1.Text = aa + "\n\r";
}
You need to use += to append it.
if (!rowold[3].ToString().Contains(aa))
{
richTextBox1.Text += aa + "\n\r";
}
or even better use
RTB.AppendText( string.Format( "....." , a , b );
Try Replacing this part of the code
if (!rowold[3].ToString().Contains(aa))
{
richTextBox1.Text = aa + "\n\r";
}
With this
if (aa!=old)
{
richTextBox1.Text = richTextBox1.Text + aa + "\n\r";
}

Categories