Copy Data from Access to an Existing SQL Server Table - c#

This code copies data from access to SQL server table.
but this code has some problems.
This code can not copy data from access to SQL server table where have data.
My SQL server table has some data and I want to add data from access to under existing data in SQL server table.
How do I add data to the existing table?
Can not read data from access 2007 or 2010.
How do I read data from access 2007/2010
OpenFileDialog openfiledialog1 = new OpenFileDialog();
openfiledialog1.Title = "select access file";
openfiledialog1.Filter = "Access 2003 (*.mdb)|*.mdb|Access 2007|*.accdb";
if (openfiledialog1.ShowDialog() == DialogResult.OK)
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openfiledialog1.FileName;
const string connectionStringDest = #"server=ahmad-pc\anfd;database = phonebook;Integrated Security = true";
using (var sourceConnection = new OleDbConnection(connectionString))
{
sourceConnection.Open();
var commandSourceData = new OleDbCommand("SELECT * from numberperson", sourceConnection);
var reader = commandSourceData.ExecuteReader();
using (var destinationConnection = new SqlConnection(connectionStringDest))
{
destinationConnection.Open();
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.ColumnMappings.Add("name", "nameperson"); //THIS A MAPPING REPLACE IT WITH YOUR NEED
bulkCopy.ColumnMappings.Add("family", "family1");
bulkCopy.DestinationTableName = "profile2";
try
{
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
reader.Close();
}
}
}
MessageBox.Show("success");
}
}

SQLBulkCopy only does Bulk inserts so any existing data should not be modified.
For MS Access > 2003 you'll need to use Microsoft ACE instead of JET

Related

c# Excel, the provider 'microsoft.ace.oledb.12.0' is not registered

I am working on a c# project where I need the user to open an Excel file and insert the data in an SQL server database. The problem is that using this connection string
("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;")
during the opening of the connection I get
the provider 'microsoft.ace.oledb.12.0' is not registered
exception, which is odd because I worked with an Access Database and used the same connection string. The Access Database Engine is installed on my PC and I even compiled at x86, am I missing something?
The reasons are as follows:
When accessing the .xlsx file with SQL SERVER, you must use
provider 'Microsoft.ACE.OLEDB.12.0' to implement.
First install AccessDatabaseEngine.exe.
Download path: http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
This provider can be seen in the database on 32-bit systems.
It cannot be seen in a 64-bit system, so you need to call
C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\DTExec.exe
to execute the package.
solution:
Open IIS Manager.
Right-click the connection pool where the application is located.
Modify "Enable 32 as application" to true.
The code shown below may help you.
Sqlconn sqlcon = new Sqlconn();
public Form1()
{
InitializeComponent();
}
string str_Excel_Path;
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//Only one file can be opened------------------------------------------
openFileDialog1.Filter = "Excel file|*.xlsx";//Set the open file filter
openFileDialog1.Title = "Open Excel file";//Set the title of the open file
openFileDialog1.Multiselect = true;//Allow multiple files to be selected
if (openFileDialog1.ShowDialog() == DialogResult.OK)//Determine whether a file is selected
{
str_Excel_Path = openFileDialog1.FileName.ToString();//Get the selected file address
textBox1.Text = str_Excel_Path;//Display the selected file address in textBox1
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
string[] P_str_Names = textBox1.Text.Split(',');//Store all selected Excel file names
string P_str_Name = "";//Store the traversed Excel file name
List<string> P_list_SheetNames = new List<string>();//Create a generic collection object to store sheet names
for (int i = 0; i < P_str_Names.Length; i++)//Iterate over all selected Excel file names
{
P_str_Name = P_str_Names[i];//The Excel file name traversed by the record
P_list_SheetNames = GetSheetName(P_str_Name);//Get all sheet names in the Excel file
for (int j = 0; j < P_list_SheetNames.Count; j++)//traverse all worksheets
{
/* if (ckbox_Windows.Checked)//Log in to SQL Server with Windows authentication
//Export worksheet contents to SQL Server
{
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data Source='" + txt_Server.Text + "';Initial Catalog='" + cbox_Server.Text + "';Integrated Security=True;");
}
else if (ckbox_SQL.Checked)//Log in to SQL Server with SQL Server authentication
{
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data Source='" + txt_Server.Text + "'Database='" + cbox_Server.Text + "';Uid='" + txt_Name.Text + "';Pwd='" + txt_Pwd.Text + "';");
}*/
ImportDataToSql(P_str_Name, P_list_SheetNames[j], "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456");
}
}
MessageBox.Show("All selected Excel sheets have been imported into SQL Server database!", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Please select the file to be imported into the database!");
}
}
//Get all worksheet names in the Excel file
private List<string> GetSheetName(string P_str_Name)
{
List<string> P_list_SheetName = new List<string>();//Create a generic collection object
//Connect to the Excel database
//OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Name + ";Extended Properties=Excel 8.0;");
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + P_str_Name + ";Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"");
olecon.Open();//Open database connection
System.Data.DataTable DTable = olecon.GetSchema("Tables");//Create a table object
DataTableReader DTReader = new DataTableReader(DTable);//Create table read object
while (DTReader.Read())
{
string p_str_sName = DTReader["Table_Name"].ToString().Replace('$', ' ').Trim();//Record the worksheet name
if (!P_list_SheetName.Contains(p_str_sName))//Determine whether the sheet name already exists in the generic collection
P_list_SheetName.Add(p_str_sName);//Add the worksheet to the pan-collection
}
DTable = null;//Clear the table object
DTReader = null;//Clear the table read object
olecon.Close();//Close the database connection
return P_list_Sheet
}
/* Import the content of the specified worksheet in Excel into the SQL Server database */
public void ImportDataToSql(string p_str_Excel, string p_str_SheetName, string p_str_SqlCon)
{
DataSet myds = new DataSet();//Create a dataset object
try
{
// get all data
//string P_str_OledbCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + p_str_Excel + ";Extended Properties=Excel 8.0;";
string P_str_OledbCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + p_str_Excel + ";Extended Properties=\"Excel 12.0;HDR=yes;IMEX=1;\"";
OleDbConnection oledbcon = new OleDbConnection(P_str_OledbCon);//Create an Oledb database connection object
string p_str_ExcelSql = "";//Record the Excel query statement to be executed
OleDbDataAdapter oledbda = null;//Create an Oledb data bridge object
p_str_ExcelSql = string.Format("select * from [{0}$]", p_str_SheetName);//Record the Excel query statement to be executed
oledbda = new OleDbDataAdapter(p_str_ExcelSql, P_str_OledbCon);//Execute Excel query using data bridge
oledbda.Fill(myds, p_str_SheetName);//Fill data
//Define variables to record the SQL statement that creates the table
string P_str_CreateSql = string.Format("create table {0}(", p_str_SheetName);
foreach (DataColumn c in myds.Tables[0].Columns)//traverse all rows in the dataset
{
P_str_CreateSql += string.Format("[{0}]text,", c.ColumnName);//Create a field in the table
}
P_str_CreateSql = P_str_CreateSql + ")";//Improve the SQL statement for creating a table
//Create SQL database connection object
using (SqlConnection sqlcon = new SqlConnection(p_str_SqlCon))
{
sqlcon.Open();//Open database connection
SqlCommand sqlcmd = sqlcon.CreateCommand();//Create an execution command object
sqlcmd.CommandText = P_str_CreateSql;//Specify the SQL data to be executed
sqlcmd.ExecuteNonQuery();//Execute operation
sqlcon.Close();//Close the database connection
}
using (SqlBulkCopy bcp = new SqlBulkCopy(p_str_SqlCon))//Import data with bcp
{
bcp.BatchSize = 100;//Number of rows per transfer
bcp.DestinationTableName = p_str_SheetName;//Define the destination table
bcp.WriteToServer(myds.Tables[0]);//Write data to SQL server data table
}
}
catch
{
MessageBox.Show("SQL Server database already exists" + p_str_SheetName + "Table!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Sqlconn code:
// private static string constr = "server=(local);Initial Catalog=D_total;Integrated Security=True";
private static string constr = "Data source=localhost;Initial Catalog=student;User ID=sa;Password=123456";
// private static string constr = "Data Source =192.168.1.201;Initial Catalog=D_total23 ;User Id=sa;Password=123";
public DataTable f1()
{
string A = "select name from master..sysdatabases";//Query this database information
return Only_Table1(A);
}
public DataTable Only_Table1(string exec)
{
System.Data.DataTable dt_jdl = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(constr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
if (con.State == ConnectionState.Open || con.State == ConnectionState.Connecting)
{
SqlDataAdapter sda2 = new SqlDataAdapter(exec, con);//All by writing stored procedures
DataSet ds2 = new DataSet();
sda2.Fill(ds2, "cxq");
dt_jdl = ds2.Tables["cxq"];
sda2.Dispose();
ds2.Dispose();
}
con.Close();
}
return dt_jdl;
}
catch (Exception EX)
{
return null;
}
}
}
Run the project:
Click the OK button to select the xml file from the folder. Click the import button to import the file into the database.

Adding uploaded by (user name or name) Automatically while uploading the Excel into SQL Server in C#

I want to upload Excel data into SQL Server with uploaded by (i.e which pick from session method)
I have created table name, country, address, uploaded by.
Normally the upload is working fine but I want to add the uploaded by value while uploading the excel bulk upload
I don't know how to insert the uploaded by value in bulk upload some one help me
This is my code:
try
{
myExcelConn.Open();
// GET DATA FROM EXCEL SHEET.
OleDbCommand objOleDB = new OleDbCommand("SELECT * FROM [Sheet1$]", myExcelConn);
// READ THE DATA EXTRACTED FROM THE EXCEL FILE.
OleDbDataReader objBulkReader = null;
objBulkReader = objOleDB.ExecuteReader();
// SET THE CONNECTION STRING.
string sCon = sqlconn;
using (SqlConnection con = new SqlConnection(sCon))
{
con.Open();
//SqlConnection p = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jetback\source\repos\Projectstudent\webdown_up_load\App_Data\upload.mdf;Integrated Security=True");
// FINALLY, LOAD DATA INTO THE DATABASE TABLE.
oSqlBulk = new SqlBulkCopy(con);
oSqlBulk.DestinationTableName = "Table3"; // TABLE NAME.
oSqlBulk.ColumnMappings.Add("name", "name");
oSqlBulk.ColumnMappings.Add("address", "address");
oSqlBulk.ColumnMappings.Add("country", "country");
oSqlBulk.WriteToServer(objBulkReader);
}
lblConfirm.Text = "DATA IMPORTED SUCCESSFULLY.";
lblConfirm.Attributes.Add("style", "color:green");
}
catch (Exception ex)
{
lblConfirm.Text = ex.Message;
lblConfirm.Attributes.Add("style", "color:red");
}
finally
{
// CLEAR.
oSqlBulk.Close();
oSqlBulk = null;
myExcelConn.Close();
myExcelConn = null;
}
It's better to use DataTable if you want to add more col when there's already data in yr dataSet:
var results = new DataTable();
using(var myExcelConn = new OleDbConnection(excCnnStr))
{
using (var cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", myExcelConn))
{
myExcelConn.Open();
var adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
}
//add new col
results.Columns.Add("uploadedBy", typeof(System.Int32));
foreach (DataRow row in results.Rows)
{
row["uploadedBy"] = loggedInUserId; // set uploader
}
using (var con = new SqlConnection(sCon))
{
con.Open();
using (var oSqlBulk = new SqlBulkCopy(con))
{
oSqlBulk.DestinationTableName = "Table3";
oSqlBulk.ColumnMappings.Add("name", "name");
oSqlBulk.ColumnMappings.Add("address", "address");
oSqlBulk.ColumnMappings.Add("country", "country");
oSqlBulk.ColumnMappings.Add("uploadedBy", "uploadedBy");
oSqlBulk.WriteToServer(results);
}
}
You will have to get from Excel and then insert into SQL.
//After objBulkReader = objOleDB.ExecuteReader();
if (objBulkReader.HasRows)
{
while (objBulkReader.Read())
{ string newname = objBulkReader[0].ToString();
string address= objBulkReader[1].ToString();
string country= objBulkReader[2].ToString();
string uploadedby=Session["uploader"].ToString();
//insert these into SQL db by SQL connection
}
}
The 0,1 and 2 in objBulkReader are column positions in Excel.

Programmatically Backup database from host in asp.net

I have a website and an SQL Server database on it. The control panel of my host is Plesk 12.5. Now, I want backup my database and store it on a special folder in my host. I've added permisson to save data to this special folder in my host control panel, and the function that I use it to create and save database backup is :
string CS = "server=localhost;database = Test;uid=***; password=***;";
string filename = "testDB.bak";
string folderPath = Server.MapPath("~/Backups/");
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
using (SqlConnection con = new SqlConnection(CS))
{
string SqlStmt = String.Format("Backup Database Test To Disk = '{0}'", folderPath + filename);
using (SqlCommand cm = new SqlCommand(SqlStmt, con))
{
try
{
con.Open();
cm.ExecuteNonQuery();
con.Close();
}
catch (Exception E)
{
Label1.Text = E.Message;
return;
}
}
}
'Backups' folder is created, but for backup, get this error: "Cannot open backup device 'C:***********.com\httpdocs\Backups\testDB.bak'. Operating system error 5(Access is denied.). BACKUP DATABASE is terminating abnormally."

Inserting Excel sheet into SQL Server database

I am trying to insert an Excel sheet into a SQL Server database from datagridview using OleDb.
The code that I use :
namespace importfromexcel
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True");
// SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
private void button2_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
}
}
private void button1_Click(object sender, EventArgs e)
{
string excelConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;data source=" + ofd.FileName + #";Extended Properties=Excel 8.0;";
// Create Connection to Excel Workbook
//We can Import excel to sql server like this
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand("Select fname,lname FROM [sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=HAMNDOSH-PC\\SQLEXPRESS;Initial Catalog=mohammed;Integrated Security=True";
// SqlCommand cmd;
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "test";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
}
My database name is : mohammed and the table name is test with two columns firstname and lastname and the Excel sheet columns is fname and lname ..
The problem is that when I execute the code and after insert the Excel sheet from button2
when I click button1 and I got an window error
vshot32-clr2.exe has stopped working
Any help please ??
I don't know if it's the root cause, but you're referencing ofd.FileName in your Click event when there's no guarantee that the dialog has a valid file selected. Since you're storing that value in a text box I would change it to:
string excelConnectionString =
#"Provider=Microsoft.Jet.OLEDB.4.0;data source="
+ textBox1.Text
+ #";Extended Properties=Excel 8.0;";
I would also verify that you're able to query the data (e.g. by writing to a text file) as a test before trying to implement bulk copy. Also be aware that the source data must have exactly the same structure (including column order) unless you supply a ColumnMapping.
Sql server has a import tool called Sql Server Data Tools... there you can find a activity to import from a excel file... very "end-user" deal, by that i mean the you can configure everything on drag and drop basis...
In your extended properties for the excel connection string, you may wish to set HDR=YES and IMEX=1. HDR=YES will read the first row in your excel sheet and read the data stored in each cell as a column name. IMEX=1 tells JET to insert the data regardless of datatype from each cell.
Have a look at this code I have written myself, it may help you.
//ExcelDA Class
public ExcelDA()
{
connString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + ofd.FileName + "; Extended Properties=" + '"' + "Excel 8.0; HDR=Yes; IMEX=1" + '"';
}
/// <summary>
/// Method used to retrieve a datatable from excel sheet
/// </summary>
public DataTable GetProductsExcel()
{
StringBuilder excBuilder = new StringBuilder();
excBuilder.Append("SELECT * FROM [Sheet1$];");
//
try
{
return ExecuteSqlStatement(excBuilder.ToString());
}
catch (Exception)
{
MessageBox.Show("Error retreiving data");
return null;
}
}
private DataTable ExecuteSqlStatement(string command)
{
using (OleDbConnection conn = new OleDbConnection(connString))
{
try
{
conn.Open();
using (OleDbDataAdapter adaptor = new OleDbDataAdapter(command, conn))
{
DataTable table = new DataTable();
adaptor.Fill(table);
return table;
}
}
catch (SqlException e)
{
throw e;
}
}
}
//SqlDA class
public void ExecuteSQLCommand(string comm)
{
try
{
using (SqlConnection conn = new SqlConnection(_connectionString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(comm, conn))
{
command.ExecuteNonQuery();
}
}
}
catch (ArgumentOutOfRangeException ex)
{
throw ex;
}
catch (ArgumentException ex)
{
throw ex;
}
catch (SqlException ex) { throw ex; }
}
public void AddNames(string fName, string sName)
{
StringBuilder sqlQuery = new StringBuilder();
//build sql insert statement here
ExecuteSQLCommand(sqlBuilder.ToString());
}
//Program class
ExcelDA reader = new ExcelDA();
DataTable names = reader.GetSuppliersExcel();
//string array to store excel row data for names
string[] arr2 = new string[2] { "", ""};
//recursive loop to retrieve each row and values from each rows columns
foreach (DataRow row in suppliers.Rows)
{
for (int i = 0; i < names.Columns.Count; i++)
{
if (i == (names.Columns.Count - 1))
{
arr2[i] = (row[i].ToString());
}
else
{
arr2[i] = (row[i].ToString());
}
}
}
try
{
sql.AddNames(arr2[0], arr2[1]);
Console.WriteLine("Added Data to SQL");
}
catch (Exception) { }

Check excel file contents before import

I am using VS2005 C# ASP.NET and SQL Server 2005.
I have a function which import Excel data. I have met a situation when the data inside is inappropriate, it will bring down the SQL Server DB.
E.g. SELECT [Username], [Password] from [userlist$] -> If an excel spreadsheet contains more than [Username] in one column or values below the columns, the server will crash.
E.G.
May I know how can I have a statement to check for this file error before uploading? Prefer if else statements for checking.
Thank you for any help or examples given.
Below is my code snippet for the excel upload:
if (FileImport.HasFile)
{
// Get the name of the Excel spreadsheet to upload.
string strFileName = Server.HtmlEncode(FileImport.FileName);
// Get the extension of the Excel spreadsheet.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension == ".xls" || strExtension == ".xlsx")
{
// Generate the file name to save.
string strUploadFileName = "C:/Documents and Settings/user01/My Documents/Visual Studio 2005/WebSites/MajorProject/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
FileImport.SaveAs(strUploadFileName);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strUploadFileName + ";Extended Properties=Excel 8.0;";
using (OleDbConnection connection =
new OleDbConnection(connStr))
{
string selectStmt = string.Format("Select [COLUMNS] FROM [userlist$]");
OleDbCommand command = new OleDbCommand(selectStmt, connection);
connection.Open();
Console.WriteLine("Connection Opened");
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<datasource>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "UserDB";
bulkCopy.WriteToServer(dr);
return;
}
}
}
Depending on the amount of data that is in the Excel spreadsheet, you could read each of the values from the column you are interested in into a Dictionary, for example, and fail the import as soon as you find the first conflict.
For example, using your existing datareeader:
Dictionary<string, string> cValues = new Dictionary<string, string>();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
while (dr.Read()) {
string sValue = dr[0].ToString();
if (cValue.ContainsKey(sValue)) {
// There is a duplicate value, so bail
throw new Exception("Duplicate value " + sValue);
} else {
cValues.Add(sValue, sValue);
}
}
}
// Now execute the reader on the command again to perform the upload
using (DbDataReader dr = command.ExecuteReader())
You should solve the cause of the problem, which is the database. Apparently, the way you store the data should be via stored procedures which handle wrongly input data.
Also, the constraints on the database tables should prohibit you from storing non-sensical data.

Categories

Resources