How to update sql database table info with excel file using file uploaded - asp.net

I am trying to update the files in the table that I have created. I am using file uploader to insert my Excel file and upload it to the database. But currently my code creates a new database table each time a file is uploaded, which I don't want it to do. I want to just update/replace the whole file in database table. How do I do this?
This is my code:
private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["nConnectionString2"].ConnectionString;
}
private void CreateDatabaseTable(DataTable dt, string tableName)
{
string sqlQuery = string.Empty;
string sqlDBType = string.Empty;
string dataType = string.Empty;
int maxLength = 0;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < dt.Columns.Count; i++)
{
dataType = dt.Columns[i].DataType.ToString();
if (dataType == "System.Int32")
{
sqlDBType = "INT";
}
else if (dataType == "System.String")
{
sqlDBType = "NVARCHAR";
maxLength = dt.Columns[i].MaxLength;
}
if (maxLength > 0)
{
sb.AppendFormat(string.Format(" {0} {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
}
else
{
sb.AppendFormat(string.Format(" {0} {1}, ", dt.Columns[i].ColumnName, sqlDBType));
}
}
sqlQuery = sb.ToString();
sqlQuery = sqlQuery.Trim().TrimEnd(',');
sqlQuery = sqlQuery + " )";
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
{
string sqlQuery = string.Empty;
StringBuilder sb = new StringBuilder();
sb.AppendFormat(string.Format("BULK INSERT {0} ", tableName));
sb.AppendFormat(string.Format(" FROM '{0}'", fileFullPath));
sb.AppendFormat(string.Format(" WITH ( FIELDTERMINATOR = '{0}' , ROWTERMINATOR = '\n' )", delimeter));
sqlQuery = sb.ToString();
using (SqlConnection sqlConn = new SqlConnection(GetConnectionString()))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileInfo fileInfo = new FileInfo(FileUpload1.PostedFile.FileName);
if (fileInfo.Name.Contains(".csv"))
{
string fileName = fileInfo.Name.Replace(".csv", "").ToString();
string csvFilePath = Server.MapPath("UploadExcelFile") + "\\" + fileInfo.Name;
//Save the CSV file in the Server inside 'MyCSVFolder'
FileUpload1.SaveAs(csvFilePath);
//Fetch the location of CSV file
string filePath = Server.MapPath("UploadExcelFile") + "\\";
string strSql = "SELECT * FROM [" + fileInfo.Name + "]";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='text;HDR=YES;'";
// load the data from CSV to DataTable
OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strCSVConnString);
DataTable dtCSV = new DataTable();
DataTable dtSchema = new DataTable();
adapter.FillSchema(dtCSV, SchemaType.Mapped);
adapter.Fill(dtCSV);
if (dtCSV.Rows.Count > 0)
{
CreateDatabaseTable(dtCSV, fileName);
Label1.Text = string.Format("The table ({0}) has been successfully created to the database.", fileName);
string fileFullPath = filePath + fileInfo.Name;
LoadDataToDatabase(fileName, fileFullPath, ",");
Label1.Text = string.Format("({0}) records has been loaded to the table {1}.", dtCSV.Rows.Count, fileName);
}
else
{
Label1.Text = "File is empty.";
}
}
else
{
Label1.Text = "Unable to recognize file.";
}
}
}

The code that creates the tables should give an error when you run it if the tables already exists as you never drop them.
That said, one solution might be to add a check to see if the table already exists in the code that creates a new table; it should be something like:
IF OBJECT_ID('TABLE', 'U') IS NULLwhere TABLEit the name of the table that you want to add, so the code might look like:
sb.AppendFormat(string.Format("IF OBJECT_ID({0}, 'U') IS NULL CREATE TABLE {0} (", tableName));
Another, possibly better, option would be to run a query to check if the table exists before you run the CreateDatabaseTable(dtCSV, fileName);statement. You can do the check by executing something like IF OBJECT_ID('tableName', 'U') IS NULL SELECT 1 ELSE SELECT 0 (this would return 1 if the table doesn't exist), and then conditionally execute the CreateDatabaseTablestatement.

Related

set a constant(same) time stamp for multiple data base rows

I'm creating an asp.net mvc4 application, that can write data into database tables from excel sheets(using sqlbulkcopy column mapping). when we select excel sheet and submit, it is writing data into database.
Now I want to set file uploaded time as timestamp for each data rows when it write data into database table.
Code:
namespace AFFEMS2_HEC.Controllers
{
public class ExcelController : Controller
{
//
// GET: /Excel/
public ActionResult Index()
{
return View();
}
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(HttpPostedFileBase FileUpload1)
{
//Upload and save the file
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string excelPath = Path.Combine(HttpContext.Server.MapPath("~/Content/"), Path.GetFileName(FileUpload1.FileName));
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
string sheet2 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[1]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[4] {
new DataColumn("Id", typeof(string)),
new DataColumn("Name", typeof(string)),
new DataColumn("Email",typeof(string)),
new DataColumn("Mobile", typeof(int)) });
string query = "SELECT s1.Id, " +
"s1.Name, " +
"s1.Mobile, " +
"s2.Email " +
"FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)";
using (OleDbDataAdapter oda = new OleDbDataAdapter(query, excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con,
SqlBulkCopyOptions.CheckConstraints|
SqlBulkCopyOptions.FireTriggers|
SqlBulkCopyOptions.KeepNulls|
SqlBulkCopyOptions.TableLock|
SqlBulkCopyOptions.UseInternalTransaction,
null))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "User1";
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
con.Open();
try
{
// Write from the source to the destination
sqlBulkCopy.WriteToServer(dtExcelData);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
return View();
}
}
}
Just create another column as "TimeStamp_Inserted" but it type should be datetime or
nvarchar
and try to replace following code snippet
string query = "SELECT s1.Id, " +
"s1.Name, " +
"s1.Mobile, " +
"s2.Email " +
"'"+DateTime.Now.ToString() +"'"+" as TimeStamp_Inserted"+
"FROM ([" + sheet1 + "] as s1 INNER JOIN [" + sheet2 + "] as s2 ON " + "s1.Id = s2.Id)";
sqlbulkcopy column mapping try to change like this
sqlBulkCopy.DestinationTableName = "User1";
sqlBulkCopy.ColumnMappings.Add("Id", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Email", "Email");
sqlBulkCopy.ColumnMappings.Add("Mobile", "Mobile");
sqlBulkCopy.ColumnMappings.Add("TimeStamp_Inserted", "TimeStamp");
con.Open();
just try it

Import a Excel sheet into MS SQL database

I have Excel 2007 and Visual Web Developer Express 2010.
I would like to import Sheet1 of an xlsx file the reader then add the data to a dataset and placing that data in a MS SQL database.
string ExcelConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
string SQLConStr = "got connection string that works";
OleDbConnection ExcelConnection = new OleDbConnection(ExcelConStr);
using (ExcelConnection)
{
string sql = string.Format("Select * FROM [{0}]", "Sheet1$");
OleDbCommand command = new OleDbCommand(sql, ExcelConnection);
ExcelConnection.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLConStr))
{
bulkCopy.DestinationTableName = "dbo.databaseName";
bulkCopy.WriteToServer(dr);
}
}
}
I need something like bulkcopy that is free and easy to use if someone may make a recommendation.
Without bulk copy it will also work.. try this it will work 100% for .csv and .xlsx both... I m using it..
string header = "No";
string sql = string.Empty;
DataTable dt = new DataTable();
string pathOnly = string.Empty;
string fileName = string.Empty;
pathOnly = Path.GetDirectoryName(path);
fileName = Path.GetFileName(path);
if (IsFirstRowHeader) { header = "Yes"; }
String cs = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=" + header + ";IMEX=1;\"";
OleDbConnection con = new OleDbConnection(cs);
if (con.State == ConnectionState.Closed) con.Open();
#region use to find sheet and fire query on sheetname
DataTable dtsheets = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dtsheets.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in dtsheets.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
if (extension == ".csv") sql = "SELECT * FROM [" + fileName + "]";
else sql = "SELECT * FROM [" + excelSheets[0] + "]";
#endregion
OleDbCommand command = new OleDbCommand(sql, con);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
dt.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dt);
con.Close();

Confused About How to insert xml value into database

I am dealing with xml files and I have found an example here.I have changed connection string and created a table named MyProducts then I have manually located my Product.xml files inside App_Data folder.When i run my program get this execption
Invalid object name 'Product'.
So in the debug mode I have noticed that myxml variable is null What am i doing wrong
protected void Button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile ;
string sql = null;
int product_ID = 0;
string Product_Name = null;
double product_Price = 0;
connetionString = "Data Source=.\\sqlexpress;Initial Catalog=Northwind;Integrated Security=sspi";
connection = new SqlConnection(connetionString);
xmlFile = XmlReader.Create(Server.MapPath("~/App_Data/Product.xml"), new XmlReaderSettings());
ds.ReadXml(xmlFile);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
product_ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
Product_Name = ds.Tables[0].Rows[i].ItemArray[1].ToString();
product_Price = Convert.ToDouble(ds.Tables[0].Rows[i].ItemArray[2]);
sql = "insert into Product values(" + product_ID + ",'" + Product_Name + "'," + product_Price + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
connection.Close();
Label1.Text = "ok";
}
As I've said in comments, you've just misspelled your table name - you table called MyProducts and you're trying to insert into Product
insert into MyProducts ...

ASP.Net insert data from form to a database Exception

I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);

Insert ADO.Net DataTable into an SQL table

The current solution i implemented is awful!
I use a for... loop for inserting records from an ADO.NET data-table into an SQL table.
I would like to insert at once the data-table into the SQL table, without iterating...
Is that possible, or am i asking too much?
You can pass the entire DataTable as a single Table Valued Parameter and insert the entire TVP at once. The following is the example from Table-Valued Parameters in SQL Server 2008 (ADO.NET):
// Assumes connection is an open SqlConnection.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories = CategoriesDataTable.GetChanges(
DataRowState.Added);
// Define the INSERT-SELECT statement.
string sqlInsert =
"INSERT INTO dbo.Categories (CategoryID, CategoryName)"
+ " SELECT nc.CategoryID, nc.CategoryName"
+ " FROM #tvpNewCategories AS nc;"
// Configure the command and parameter.
SqlCommand insertCommand = new SqlCommand(
sqlInsert, connection);
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
"#tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.CategoryTableType";
// Execute the command.
insertCommand.ExecuteNonQuery();
}
TVP are only available in SQL 2008.
I think you are looking for SQLBulkCopy.
SqlBulkCopy is the simplest solution.
using (SqlConnection dbConn = new SqlConnection(connectionString))
{
dbConn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(dbConn))
{
bulkCopy.DestinationTableName =
"dbo.MyTable";
try
{
bulkCopy.WriteToServer(myDataTable, DataRowState.Added);
}
catch (Exception ex)
{
myLogger.Error("Fail to upload session data. ", ex);
}
}
}
You can create SqlBulkCopyColumnMapping if the columns in your DataTable don't match your database table.
You can also try the following method.
private void button1_Click(object sender, EventArgs e)
{
tabevent();
DataSet ds = new DataSet();
DataTable table = new DataTable("DataFromDGV");
ds.Tables.Add(table);
foreach (DataGridViewColumn col in dataGridView1.Columns)
table.Columns.Add(col.HeaderText, typeof(string));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
table.Rows.Add(row);
foreach (DataGridViewCell cell in row.Cells)
{
table.Rows[row.Index][cell.ColumnIndex] = cell.Value;
}
}
// DataTable ds1changes = ds1.Tables[0].GetChanges();
if (table != null)
{
SqlConnection dbConn = new SqlConnection(#"Data Source=wsswe;Initial Catalog=vb;User ID=sa;Password=12345");
SqlCommand dbCommand = new SqlCommand();
dbCommand.Connection = dbConn;
foreach (DataRow row in table.Rows)
{
if (row["quantity"] != null && row["amount"]!=null && row["itemname"]!=null)
{
if (row["amount"].ToString() != string.Empty)
{
dbCommand.CommandText =
"INSERT INTO Bill" +
"(Itemname,Participants,rate,Quantity,Amount)" +
"SELECT '" + Convert.ToString(row["itemname"]) + "' AS Itemname,'" + Convert.ToString(row["Partcipants"]) + "' AS Participants,'" + Convert.ToInt32(row["rate"]) + "' AS rate,'" +
Convert.ToInt32(row["quantity"]) + "' AS Quantity,'" + Convert.ToInt32(row["amount"]) + "' AS Amount";
dbCommand.Connection.Open();
dbCommand.ExecuteNonQuery();
if (dbCommand.Connection.State != ConnectionState.Closed)
{
dbCommand.Connection.Close();
}
MessageBox.Show("inserted");
}
}
}
}
}

Resources