资源介绍
windows ce的开发int startTickCount = Environment.TickCount;
// 创建源 SQL Server 数据库连接对象
string srcConnString = "Data Source=(local);Initial Catalog=Northwind;User Id=sa;Password=123;";
SqlConnection srcConnection = new SqlConnection(srcConnString);
// 创建目标 SQL Server Compact Edition 数据库连接对象
string destConnString = @"Data Source=Northwind.sdf";
SqlCeConnection destConnection = new SqlCeConnection(destConnString);
VerifyDatabaseExists(destConnString);
srcConnection.Open();
destConnection.Open();
// 复制数据
CopyTable(srcConnection, destConnection, "SELECT * FROM Products", "Products");
CopyTable(srcConnection, destConnection, "SELECT * FROM Employees", "Employees");
srcConnection.Close();
destConnection.Close();
MessageBox.Show((Environment.TickCount - startTickCount).ToString());
}
///
/// 将源数据库表的数据复制到 SQL Server Compact Edition 数据库的表中。
///
/// 源数据库连接接对象。
/// 目标 SQL Server Compact Edition 数据库连接对象。
/// 源数据的查询语句。
/// 目标数据库表名称。
/// 本方法假设目标 SQL Server Compact Edition 数据库的表已经存在。
public static void CopyTable(
IDbConnection srcConnection,
SqlCeConnection destConnection,
string queryString,
string destTableName)
{
IDbCommand srcCommand = srcConnection.CreateCommand();
srcCommand.CommandText = queryString;
SqlCeCommand destCommand = destConnection.CreateCommand();
destCommand.CommandType = CommandType.TableDirect; //基于表的访问,性能更好
destCommand.CommandText = destTableName;
try
{
IDataReader srcReader = srcCommand.ExecuteReader();
SqlCeResultSet resultSet = destCommand.ExecuteResultSet(
ResultSetOptions.Sensitive | //检测对数据源所做的更改
ResultSetOptions.Scrollable | //可以向前或向后滚动
ResultSetOptions.Updatable); //允许更新数据
object[] values;
SqlCeUpdatableRecord record;
while (srcReader.Read())
{
// 从源数据库表读取记录
values = new object[srcReader.FieldCount];
srcReader.GetValues(values);
// 把记录写入到目标数据库表
record = resultSet.CreateRecord();
record.SetValues(values);
resultSet.Insert(record);
}
srcReader.Close();
resultSet.Close();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
public static void VerifyDatabaseExists(string connectionString)
{
using (SqlCeConnection connection = new SqlCeConnection(connectionString))
{
if (!File.Exists(connection.Database))
{
using (SqlCeEngine engine = new SqlCeEngine(connection.ConnectionString))
{
engine.CreateDatabase();
string[] commands = Properties.Resources.DbSchema.Split(';');
SqlCeCommand command = new SqlCeCommand();
command.Connection = connection;
connection.Open();
string query;
for (int i = 0; i < commands.Length; i++)
{
query = commands[i].Trim();
if (!string.IsNullOrEmpty(query))
{
command.CommandText = query;
command.ExecuteNonQuery();
}
}
}
}
}