Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Wednesday, August 14, 2013

Import MS Excel Data to SQL Server Table using C#

If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow the below steps:
Step 1: Let’s take an example to import data to SQL Server table. I am going to import student information data from an MS Excel sheet to the tStudent SQL table:
Step 2: Now design a tStudent table in SQL Server
CREATE TABLE
(
STUDENT VARCHAR(64),
ROLLNO VARCHAR(16),
COURSE VARCHAR(32),
)
Your MS Excel sheet and SQL table are ready, now it’s time to write C# code to import the Excel sheet into the tStudent table.
Step 3: Add these two namespaces in your class file:
USING SYSTEM.DATA.OLEDB;
USING SYSTEM.DATA.SQLCLIENT;
Step 4: Add below method in your class file, you can call this method from any other class and pass the Excel file path:
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 student,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=DBServerName;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
    }
}
In the above function you have to pass the MS Excel file path as a parameter. If you want to import your data by providing the client access to select the Excel file and import, then you might have to use the ASP.NET File control and upload the Excel file on the server in some temp folder, then use the file path of the uploaded Excel file and pass the path in the above function. Once data import is complete then you can delete the temporary file.
The above method first deletes the existing data from the destination table, then imports the Excel data into the same table.

Thursday, August 8, 2013

Backup your SQL Server Database using ASP.NET

Description :
When User Clicks on Button, Directory is created on D drive if it is not exist else backup database is saved in that folder.

.cs Code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;

namespace Backup
{
    public partial class _Default : System.Web.UI.Page
    {
        string DbName = "CBS";
        SqlConnection conStr = new SqlConnection(ConfigurationManager.ConnectionStrings["CBSConnectionString"].ConnectionString);
        DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnBackup_Click(object sender, EventArgs e)
        {
            string DestDir = "D:\\Backupdb";
            if (!System.IO.Directory.Exists(DestDir))
            {
                System.IO.Directory.CreateDirectory("D:\\Backupdb");
                MessageBox.Show("Directory is Created.");
            }
            try
            {
                conStr.Open();
                string cmdStr = "BACKUP DATABASE CBS TO DISK='"+DestDir+"\\"+DateTime.Now.ToString("ddMMyyyy_HHmmss")+".Bak'";
                SqlCommand cmd = new SqlCommand(cmdStr,conStr);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Backup is done successfully..");
            }
            catch(SqlException exc)
            {
                MessageBox.Show(exc.Message);
            }
            finally
            {
                conStr.Close();
            }
        }
    }
}

ASPX Code :

<p>Click to Backup your database :</p>
    <asp:Button ID="btnBackup" runat="server" onclick="btnBackup_Click"
        Text="Backup" />

Screen Shot: