将 SQL 数据库导出到 WinForm DataSet,然后使用 DataSet 导出到 MDB 数据库 [英] Export SQL DataBase to WinForm DataSet and then to MDB Database using DataSet

查看:86
本文介绍了将 SQL 数据库导出到 WinForm DataSet,然后使用 DataSet 导出到 MDB 数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序是一个依赖于数据库的 winform 应用程序.在应用程序启动时,它连接到服务器上的 SQL 数据库并将此信息放入数据集/数据表中.

My application is a winform app that relies on a database. At startup of the application it connects to an SQL Database on the server and put this information in a DataSet/DataTable.

如果由于某种原因无法访问服务器上的数据库,则该应用程序具有内置故障转移功能,它将从本地数据库获取其信息.

If for some reason the database on the server is not accessible, the application has a built in failover and it will get its information from the local database.

如果,在正常情况下,我启动该工具,它将从 sql 数据库中读取,并且如果它已在服务器上更新(一个单独的代码片段对此进行检查),它应该确保本地数据库是最新的并且这就是问题开始的地方..(见下文)

If, in a normal scenario, I start the tool it will read from the sql database and if it has been updated on the server (a seperate snippet checks this), it should make sure the local database is up to date and this is where the problem starts.. (see below)

这部分工作正常并作为上下文添加 - 这是我们连接到 SQL 数据库的地方

    public static DataSet dtsTableContents;
    public static DataTable CreateDatabaseSQLConnection()
    {
        try
        {
            string strSqlConnectionString = "Data Source=MyLocation;Initial Catalog=MyCatalog;User=MyUser;Password=MyPassword;";
            SqlCommand scoCommand = new SqlCommand();
            scoCommand.Connection = new SqlConnection(strSqlConnectionString);
            scoCommand.Connection.Open();
            string strQueryToTable = "SELECT * FROM " + strTableName;
            dtsTableContents = new DataSet();
            SqlCommand scmTableInformation = new SqlCommand(strQueryToTable, scnConnectionToDatabase);
            SqlDataAdapter sdaTableInformation = new SqlDataAdapter(scmTableInformation);
            scnConnectionToDatabase.Open();
            sdaTableInformation.Fill(dtsTableContents, strTableName);
            DataTable dttTableInformation = dtsTableContents.Tables[strTableName];
            scnConnectionToDatabase.Close();
            return dttTableInformation;
        }
        catch
        {
            return null;
        }
    }

此代码段是从我的本地数据库读取的故障转移方法的一部分...

This snippet is part of the failover method that reads from my local database...

这部分工作正常并作为上下文添加 - 这是我们连接到 MDB 数据库的地方

public static DataTable CreateDatabaseConnection()
    {
        try
        {
            string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyLocation;Persist Security Info=True;JET OLEDB:Database Password=MyPassword;"
            odcConnection = new OleDbConnection(ConnectionString);
            odcConnection.Open();
            string strQueryToTable = "SELECT * FROM " + strTableName;
            DataSet dtsTableContents = new DataSet();
            OleDbCommand ocmTableInformation = new OleDbCommand(strQueryToTable, ocnConnectionToDatabase);
            OleDbDataAdapter odaTableInformation = new OleDbDataAdapter(ocmTableInformation);
            ocnConnectionToDatabase.Open();
            odaTableInformation.Fill(dtsTableContents, strTableName);
            DataTable dttTableInformation = dtsTableContents.Tables[strTableName];
            ocnConnectionToDatabase.Close();
            return dttTableInformation;
        }
        catch
        {
            return null;
        }
    }

从我的 CreateDatabaseSQLConnection() 我有一个数据集.该数据集经过验证以包含来自服务器数据库的所有信息.现在我一直在谷歌搜索,发现自己试图根据这篇文章使用此代码更新本地数据库:http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update(v=vs.71).aspx

From my CreateDatabaseSQLConnection() I have a DataSet. This DataSet is verified to contain all the information from the server database. Now I have been googling around and found myself trying to use this code to update the local database based on this article: http://msdn.microsoft.com/en-us/library/system.data.common.dataadapter.update(v=vs.71).aspx

public static void UpdateLocalDatabase(string strTableName)
    {
        try
        {
            if (CreateDatabaseConnection() != null)
            {
                string strQueryToTable = "SELECT * FROM " + strTableName;
                OleDbDataAdapter odaTableInformation = new OleDbDataAdapter();
                odaTableInformation.SelectCommand = new OleDbCommand(strQueryToTable, odcConnection);
                OleDbCommandBuilder ocbCommand = new OleDbCommandBuilder(odaTableInformation);
                odcConnection.Open();
                odaTableInformation.Update(dtsTableContents, strTableName);
                odcConnection.Close();
            }
        }
        catch { }
    }

此代码段无错误运行,但似乎没有任何改变.此外,运行此步骤所需的时间需要几毫秒,我认为这需要更长的时间.

This snippet runs error-free but it does not seem to change anything. Also the time it takes to run this step takes like milliseconds and I would think this to take longer.

我正在使用从我的 SQL 连接获得的数据集,这个数据集我试图写入我的本地数据库.

I am using the DataSet I obtained from my SQL Connection, this DataSet I am trying to write to my local database.

可能是因为这是一个来自 SQL 连接的数据集,而我无法通过我的 OleDbAdapter 将其写入我的 mdb 连接,或者我只是在这里遗漏了明显的内容?

Might it be the fact that this is a DataSet from an SQL connection and that I can't write this to my mdb connection via my OleDbAdapter or am I just missing the obvious here?

感谢任何帮助.

谢谢,

凯文

推荐答案

在无休止地尝试使用 DataAdapter.Update(Method) 之后我放弃了.. 我决定使用 sdf 文件而不是 mdb.

After endlessly trying to use the DataAdapter.Update(Method) I gave up.. I settled for using an sdf file instead of an mdb.

如果我需要更新我的数据库,我会删除本地数据库,使用相同的连接字符串创建一个新数据库.然后我遍历数据集中的表,从中读取列名和类型,并基于此创建表.

If I need to update my database, I remove the local database, create a new one, using the same connectionstring. Then I loop over the tables in my dataset, read the column names and types from it and create tables based on that.

在此之后,我遍历我的数据集并插入我用来自服务器的信息填充的数据集的内容.下面是代码,这只是作为概念证明的快速而肮脏",但它适用于我的场景.

After this I loop over my dataset and insert the contents of my dataset which I filled with the information from the server. Below is the code, this is just 'quick and dirty' as a proof of concept but it works for my scenario.

public static void RemoveAndCreateLocalDb(string strLocalDbLocation)
    {
        try
        {
            if (File.Exists(strLocalDbLocation))
            {
                File.Delete(strLocalDbLocation);
            }
            SqlCeEngine sceEngine = new SqlCeEngine(@"Data Source= " + strLocalDbLocation + ";Persist Security Info=True;Password=MyPass");
            sceEngine.CreateDatabase();
        }
        catch
        { }
    }

public static void UpdateLocalDatabase(String strTableName, DataTable dttTable)
    {
        try
        {

            // Opening the Connection
            sceConnection = CreateDatabaseSQLCEConnection();
            sceConnection.Open();

            // Creating tables in sdf file - checking headers and types and adding them to a query
            StringBuilder stbSqlGetHeaders = new StringBuilder();
            stbSqlGetHeaders.Append("create table " + strTableName + " (");
            int z = 0;
            foreach (DataColumn col in dttTable.Columns)
            {
                if (z != 0) stbSqlGetHeaders.Append(", "); ;
                String strName = col.ColumnName;
                String strType = col.DataType.ToString();
                if (strType.Equals("")) throw new ArgumentException("DataType Empty");
                if (strType.Equals("System.Int32")) strType = "int";
                if (strType.Equals("System.String")) strType = "nvarchar (100)";
                if (strType.Equals("System.Boolean")) strType = "nvarchar (15)";
                if (strType.Equals("System.DateTime")) strType = "datetime";
                if (strType.Equals("System.Byte[]")) strType = "nvarchar (100)";

                stbSqlGetHeaders.Append(strName + " " + strType);
                z++;
            }
            stbSqlGetHeaders.Append(" )");
            SqlCeCommand sceCreateTableCommand;
            string strCreateTableQuery = stbSqlGetHeaders.ToString();
            sceCreateTableCommand = new SqlCeCommand(strCreateTableQuery, sceConnection);

            sceCreateTableCommand.ExecuteNonQuery();


            StringBuilder stbSqlQuery = new StringBuilder();
            StringBuilder stbFields = new StringBuilder();
            StringBuilder stbParameters = new StringBuilder();

            stbSqlQuery.Append("insert into " + strTableName + " (");

            foreach (DataColumn col in dttTable.Columns)
            {
                stbFields.Append(col.ColumnName);
                stbParameters.Append("@" + col.ColumnName.ToLower());
                if (col.ColumnName != dttTable.Columns[dttTable.Columns.Count - 1].ColumnName)
                {
                    stbFields.Append(", ");
                    stbParameters.Append(", ");
                }
            }
            stbSqlQuery.Append(stbFields.ToString() + ") ");
            stbSqlQuery.Append("values (");
            stbSqlQuery.Append(stbParameters.ToString() + ") ");

            string strTotalRows = dttTable.Rows.Count.ToString();

            foreach (DataRow row in dttTable.Rows)
            {
                SqlCeCommand sceInsertCommand = new SqlCeCommand(stbSqlQuery.ToString(), sceConnection);
                foreach (DataColumn col in dttTable.Columns)
                {
                    if (col.ColumnName.ToLower() == "ssma_timestamp")
                    {
                        sceInsertCommand.Parameters.AddWithValue("@" + col.ColumnName.ToLower(), "");
                    }
                    else
                    {
                        sceInsertCommand.Parameters.AddWithValue("@" + col.ColumnName.ToLower(), row[col.ColumnName]);
                    }
                }
                sceInsertCommand.ExecuteNonQuery();
            }
        }
        catch { }
    }

这篇关于将 SQL 数据库导出到 WinForm DataSet,然后使用 DataSet 导出到 MDB 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆