search
HomeDatabaseMysql Tutorial如何将数据导入到 SQL Server Compact Edition 数据库中(四)

系列文章导航: 如何将数据导入到 SQL Server Compact Edition 数据库中(一) 如何将数据导入到 SQL Server Compact Edition 数据库中(二) 如何将数据导入到 SQL Server Compact Edition 数据库中(三) 摘要:在本系列文章的第一篇和第二篇为了提高数据写

系列文章导航:
如何将数据导入到 SQL Server Compact Edition 数据库中(一)
如何将数据导入到 SQL Server Compact Edition 数据库中(二)
如何将数据导入到 SQL Server Compact Edition 数据库中(三)

摘要:在本系列文章的第一篇和第二篇为了提高数据写入的性能,我使用了 SqlCeResultSet 基于表的数据写入方式,而不是使用常规的 Insert 语句。使用 SqlCeResultSet 写入数据确实方便又快速,但是必须保证从源数据库查询的结果集(通过 Select 查询语句)跟目标数据库(SQL Server Compact Edition)表的字段先后顺序一致。如果不一致,可能会导致数据导入出错;即便是导入成功,数据跟原来的字段位置也对不上。所以,我觉得有必要给大家介绍常规的 Insert 语句数据插入方式,解决 SqlCeResultSet 存在的问题。

在第三篇文章中,我们学习了 IDataReader.GetSchemaTable 方法,它可以返回一个描述了 DataReader 查询结果中各列的元数据的 DataTable。在前面的文章介绍的数据导入方法中,都是使用 DataReader 从源数据库读取数据。那么从这个 DataReader 获取的 SchemaTable 信息,就可以用于生成插入数据的 Insert 语句,前提是源数据库和目标数据库的表字段名称一致,字段的先后顺序可以不一样。以下是根据 SchemaTable 生成 Insert 语句的代码:

// 通过 DataReader 获取 SchemaTable 信息
srcReader = srcCommand.ExecuteReader(CommandBehavior.KeyInfo);
DataTable scheamTable 
= srcReader.GetSchemaTable();

// 生成 SQL Server Compact Edition 数据插入 SQL 语句
StringBuilder sbFields = new StringBuilder();
StringBuilder sbParams 
= new StringBuilder();
string field, param;
DataRow schemaRow;
for (int i = 0; i  scheamTable.Rows.Count; i++)
{
    
if (i != 0)
    {
        sbFields.Append(
"");
        sbParams.Append(
"");
    } 

    schemaRow 
= scheamTable.Rows[i];
    field 
= string.Format("[{0}]", schemaRow["ColumnName"]); //字段名称
    param = "@" + ((string)schemaRow["ColumnName"]).Replace(" ""_"); //参数名称
    sbFields.Append(field);
    sbParams.Append(param);
    destCommand.Parameters.Add(param, 
null);


string insertSql = string.Format("INSERT INTO [{0}]({1}) VALUES({2})", destTableName, sbFields, sbParams);
destCommand.CommandText 
= insertSql; 

生成 Insert 语句的代码很简单,这里就不再详细说明了。准备好了 Insert 语句,就可以开始从源数据库取数据并写入目标数据库了。这里我使用了 DataReader.GetValues 方法一次性读取一整行数据,再给 Insert 命令的参数赋值。代码如下所示:

// 执行数据导入
object[] values;
while (srcReader.Read())
{
    values 
= new object[srcReader.FieldCount];
    srcReader.GetValues(values);
    
for (int i = 0; i  values.Length; i++)
    {
        destCommand.Parameters[i].Value 
= values[i];
    }
    destCommand.ExecuteNonQuery();
}

本文的主要内容到这里已经介绍完了,我们可以结合第三篇文章介绍的根据 SchemaTable 自动生成创建表结构的 SQL 语句的代码,在导入数据前先自动创建数据表结构。相关的代码如下:

// 通过 DataReader 获取 SchemaTable 信息
srcReader = srcCommand.ExecuteReader(CommandBehavior.KeyInfo);
DataTable scheamTable = srcReader.GetSchemaTable();


// 创建 SQL Server Compact Edition 表结构
SqlCeCommand command = destConnection.CreateCommand();
command.CommandText 
= GenerateTableSchemaSql(scheamTable);
command.ExecuteNonQuery();

// 生成 SQL Server Compact Edition 数据插入 SQL 语句
StringBuilder sbFields = new StringBuilder();
StringBuilder sbParams = new StringBuilder();
......

通过遍历 SQL Server 2000 的 Northwind 数据库的每个用户表,并将每个表的数据导入到一个 SQL Server Compact Edition 数据文件 Northwind.sdf 中。代码如下所示:

// 创建源 SQL Server 数据库连接对象
string srcConnString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
SqlConnection srcConnection 
= new SqlConnection(srcConnString);

// 创建目标 SQL Server Compact Edition 数据库连接对象
string destConnString = @"Data Source=C:/Northwind.sdf";
SqlCeConnection destConnection 
= new SqlCeConnection(destConnString);

// 创建 SQL Server Compact Edition 数据文件
VerifyDatabaseExists(destConnString);

srcConnection.Open();
destConnection.Open();

// 复制数据
string[] tableNames = GetTableNames(srcConnection);
string query;
for (int i = 0; i  tableNames.Length; i++)
{
    query 
= string.Format("SELECT * FROM [{0}]", tableNames[i]);
    CopyTable(srcConnection, destConnection, query, tableNames[i]);
}

srcConnection.Close();
destConnection.Close();

同第二篇文章相比,本文中的 VerifyDatabaseExists 方法只创建 SQL Server Compact Edition 数据文件,不批量创建表结构,因为我们用上了“自动”的方法,不需要预先准备好创建表结构的 SQL 脚本。GetTableNames 和 GenerateTableSchemaSql 方法跟第三篇文章的一样,这里不再解释。

总结:本文介绍了一种比 SqlCeResultSet 更安全的数据写入方式,并结合了第三篇文章中介绍的自动生成创建数据库表结构的 SQL 语句的方法,向大家展示了一种比较完善的 SQL Server Compact Edition 数据导入方法。在后续的文章中我会继续深入下去,提供本方案在实际应用中面临的问题的解决方法。

示例代码下载:sqlce_data_import4.rar

作者:黎波
博客:http://upto.cnblogs.com/
日期:2008年2月9日

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.