如何在数据库中保存DataSet中的数据

时间:2014-03-02 10:58:54

标签: c# ado.net dataset dataadapter

我只想将Excel工作簿中的数据导入数据集并保存到数据库。令我困惑的是,我已经将dataadapter参数连接到Excel,成功导入数据(HasChanges()= True),我不知道接下来该做什么 - 我应该打开与dbMain.sfd的新连接(SQL压缩数据库与table NamesTable获取数据),制作新的dataadapter?

我知道这很简单,也许在构建这段代码这么多个小时后,我太模糊了,无法做到正确。任何帮助,特别是代码示例,非常感谢。

    static void accesData()
    {

        //  1. OleDbConnection argument constructor
        string Provider = "Provider=Microsoft.ACE.OLEDB.12.0.;";
        string Source = @"Data Source=C:\Users\zenon\Desktop\People.xlsx;";
        string Rest = "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";

        //  2. Beginning of connection. Create OleDbConnection object with connectionstring as argument

    using(OleDbConnection connection = new OleDbConnection(Provider+Source+Rest)) 
    {
            // a) Open connection
            connection.Open(); 

            // b) Create OleDbCommand sql query object
            OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$] WHERE Name='John' OR Name='Maciej'", connection); 

            //  c) Create adapter object taking query object as argument - it stores data now
            OleDbDataAdapter adapter = new OleDbDataAdapter(command); //create adapter object


            //***Clear Dataset
            ds.Clear();
            MessageBox.Show("Dataset zawiera rowsów " + ds.NamesTable.Rows.Count + ".");
            ds.NamesTable.AcceptChanges();

            //  e) Fill Table in Dataset with data from adapter. Make dataset dirty.
            adapter.AcceptChangesDuringFill = false;
            adapter.Fill(ds.NamesTable);

            //  f) Check how many (if any) rows where inserted into db

            MessageBox.Show("Dataset zawiera rowsów " + ds.NamesTable.Rows.Count + ".");

            bool zmiany = ds.HasChanges();


    // I added code to pass data from database to dataset but i get Syntax error in INSERT INTO statement. Is that the way to do it?


             string Provider2 = "Provider=Microsoft.SQLSERVER.CE.OLEDB.4.0.;";
            string Source2 = @"Data Source=C:\Users\zenon\Desktop\aaa     PS_C#\AccDB\AccDB\dbMain.sdf";

            using (OleDbConnection con2 = new OleDbConnection(Provider2 + Source2))
            {
            con2.Open();
            OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
            adapter.Update(ds, "NamesTable");

            }

    }
}

0 个答案:

没有答案