Search This Blog

2010/01/17

Tranferring data from sql server to ms Access with C#:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;

namespace MSACCESS
{
class Program
{
static void Main(string[] args)
{
string strDestPath = "I:\\Trial\\school.mdb";
SqlConnection sqlcon=new SqlConnection("Data Source=(Local);Integrated Security=SSPI;Initial Catalog=sangram") ;
sqlcon.Open();
SqlCommand sqlcmd = new SqlCommand("select * from course", sqlcon);
SqlDataReader sqldr = sqlcmd.ExecuteReader();
LoadFromSql(sqldr,strDestPath,"course");
Console.ReadKey();
}

private static void LoadFromSql(SqlDataReader dr1, string Path,string table)
{
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;Data Source = " + Path );
olecon.Open();

OleDbCommand olecmd = new OleDbCommand();
olecmd.Connection = olecon;

string strCno,strCname,strDuration,strFees;

while (dr1.Read())
{
string strCmd;

strCno=dr1[0].ToString();
strCname = dr1[1].ToString();
strDuration = dr1[2].ToString();
strFees = dr1[3].ToString();

strCmd = "Insert into course values(" + strCno + ",'" + strCname+ "'," + strDuration+ "," + strFees + ")";
olecmd.CommandText = strCmd;

try
{
olecmd.ExecuteNonQuery();
}
catch( OleDbException oleEx)
{
Console.WriteLine(oleEx.Message);
}

}


}
}
}

No comments:

Post a Comment