<script>window.onerror = function() { return true; };</script> body {margin:0;overflow:auto;font:normal 14px Verdana;background:#fff;padding:2px 4px 0;}body, p, font, div, li { line-height: 150%;}body, td, th {color:#000000;}.i {width:100%;*width:auto;table-layout:fixed;}pre {white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;}a { color: -moz-hyperlinktext !important;text-decoration: -moz-anchor-decoration;}


操作SQL Server Mobile数据库的常用C#代码


1. 创建数据库

// 创建数据库 
 
 File.Delete("Test.sdf"); 
 
 SqlCeEngine engine = new SqlCeEngine( 
 
     "Data Source='Test.sdf';LCID=1033;Password=/"s$;2'!dS64/";Encrypt=TRUE;"); 
 
 engine.CreateDatabase();


2. 验证和修复数据库

// 验证和修复数据库 
 
 SqlCeEngine engine = new SqlCeEngine("Data Source=AdventureWorks.sdf"); 
 
 if (false == engine.Verify()) 
 
 { 
 
     MessageBox.Show("Database is corrupted."); 
 
     engine.Repair(null, RepairOption.RecoverCorruptedRows); 
 
 }


3. 压缩数据库
// 压缩数据库
// 通过从现有文件新建数据库文件来回收 SQL Server Mobile 数据库中浪费的空间。
// 此方法还可用来更改数据库的排序顺序、加密或密码设置。
// 该连接字符串指定一个指向将由此方法创建的目标数据库的连接。
// 如果指定的数据库已经存在或者具有相同名称的另一文件已经存在,则会引发异常。
// 如果为连接字符串传递空字符串,则新的数据库文件将改写旧的数据库文件,
// 但名称保持不变。

SqlCeEngine engine = new SqlCeEngine("Data Source=AdventureWorks.sdf"); 
 
 //engine.Compact(null); 
 
 engine.Compact("Data Source=; 
 Password=a@3!7f$dQ ;");


4. 收缩数据库


// 收缩数据库
// 通过将空页移动到文件的结尾然后截断该文件,
// 来回收 SQL Server Mobile 数据库中浪费的空间。
// 与 Compact 方法不同,Shrink 方法不创建临时数据库文件,
// 而是将所有空页和未分配的页都移到了文件的结尾,然后截断,从而减小数据库的总大小。
SqlCeEngine engine = new SqlCeEngine("Data Source=AdventureWorks.sdf");
engine.Shrink();


5. 合并复制

// 合并复制 
 
 // 实例化并配置 SqlCeReplication 对象 
 
 SqlCeReplication repl = new SqlCeReplication(); 
 
 repl.InternetUrl = " 
 http://www.adventure-works.com/sqlmobile/sqlcesa30.dll "; 
 
 repl.InternetLogin = "MyInternetLogin"; 
 
 repl.InternetPassword = ""; 
 
 repl.Publisher = "MyPublisher"; 
 
 repl.PublisherDatabase = "MyPublisherDatabase"; 
 
 repl.PublisherLogin = "MyPublisherLogin"; 
 
 repl.PublisherPassword = ""; 
 
 repl.Publication = "MyPublication"; 
 
 repl.Subscriber = "MySubscriber"; 
 
 repl.SubscriberConnectionString = "Data Source=MyDatabase.sdf"; 
 

  // 创建一个本地 SQL Server Mobile 数据库的订阅 
 
 repl.AddSubscription(AddOption.CreateDatabase); 
 

  // 跟 SQL Server 数据库进行同步 
 
 repl.Synchronize(); 
 

  // 清理 repl 对象 
 
 repl.Dispose(); 
 

  6. 远程数据访问(RDA) 
 
 // 远程数据访问 
 
 // 实例化并配置 SqlCeRemoteDataAccess 对象 
 
 SqlCeRemoteDataAccess rda = new SqlCeRemoteDataAccess(); 
 
 rda.InternetUrl = " 
 http://www.adventure-works.com/sqlmobile/sqlcesa30.dll "; 
 
 rda.InternetLogin = "MyInternetLogin"; 
 
 rda.InternetPassword = ""; 
 
 rda.LocalConnectionString = "Data Source=MyDatabase.sdf"; 
 

  // 从 SQL Server 下载数据 
 
 rda.Pull( 
 
     "Employees", 
 
     "SELECT * FROM DimEmployee", 
 
     "Provider=sqloledb;server=MySqlServer;database=AdventureWorks;uid=sa;pwd=;", 
 
     RdaTrackOption.TrackingOnWithIndexes, 
 
     "ErrorTable"); 
 

  // 
 
 // 修改本地数据 
 
 // 
 

  // 将已修改的数据上传到 SQL Server 
 
 rda.Push( 
 
     "DimEmployee", 
 
 "Provider=sqloledb;server=MySqlServer;database=AdventureWorks;uid=sa;pwd=;"); 
 

  // 提交 SQL 语句在 SQL Server 上执行 
 
 rda.SubmitSql( 
 
     "CREATE TABLE MyRemoteTable (colA int)", 
 
     "Provider=sqloledb;server=MySqlServer;database=AdventureWorks;uid=sa;pwd=;");


7. 使用 SqlCeResultSet

// 使用 SqlCeResultSet 
 
 // 创建 SQL Server Mobile 数据库连接 
 
 SqlCeConnection conn = new SqlCeConnection("Data Source=Northwind.sdf"); 
 

  // 创建并配置 SqlCeCommand 对象 
 
 SqlCeCommand cmd = conn.CreateCommand(); 
 
 cmd.CommandText = "SELECT * FROM Orders"; 
 

  // 创建 SqlCeResultSet 对象,并配置为可滚动、可更新、检测数据源更改 
 
 ResultSetOptions options = ResultSetOptions.Scrollable | 
 
                                          ResultSetOptions.Sensitive | 
 
                                          ResultSetOptions.Updatable; 
 
 SqlCeResultSet resultSet = cmd.ExecuteResultSet(options); 
 

  // 创建 ResultSetView 对象,配置为只显示序号为 1,3,5,8 的列 
 
 ResultSetView resultSetView = resultSet.ResultSetView; 
 
 int[] ordinals = new int[] { 1,3,5,8}; 
 
 resultSetView.Ordinals = ordinals; 
 

  // 将 ResultSetView 绑定到 DataGrid 控件 
 
 this.dataGrid.DataSource = resultSetView;


8. 处理 SqlCeException

// 处理 SqlCeException 
 
 public static void ShowErrors(SqlCeException e) 
 
 { 
 
     SqlCeErrorCollection errs = e.Errors; 
 

      StringBuilder bld = new StringBuilder(); 
 
     Exception inner = e.InnerException; 
 

      foreach (SqlCeError err in errs) 
 
     { 
 
         // 标识错误类型的 HRESULT 值,这些错误不是 SQL Server CE 固有的 
 
         bld.Append("/r/nError Code: ").Append(err.HResult.ToString("X")); 
 
         // 对错误进行描述的文本 
 
         bld.Append("/r/nMessage: ").Append(err.Message); 
 
         // 获取 SqlCeError 的本机错误号 
 
         bld.Append("/r/nMinor Err.: ").Append(err.NativeError); 
 
         // 生成错误的提供程序的名称 
 
         bld.Append("/r/nSource: ").Append(err.Source); 
 

          // 遍历前三个错误参数。SQL Server CE 使用错误参数来提供有关错误的其他详细信息。 
 
         foreach (int numPara in err.NumericErrorParameters) 
 
         { 
 
             // 虽然错误可能存在参数,但并非发生的所有错误都返回参数。 
 
             // 如果发生某个错误时没有返回任何参数,则该数组的值为 0。 
 
             if (numPara != 0) 
 
             { 
 
                 bld.Append("/r/nNum. Par.: ").Append(numPara); 
 
             } 
 
         } 
 

          // 遍历最后三个错误参数。SQL Server CE 使用错误参数来提供有关错误的其他详细信息。 
 
         foreach (string errPara in err.ErrorParameters) 
 
         { 
 
             // 虽然错误可能存在参数,但并非发生的所有错误都返回参数。 
 
             // 如果发生某个错误时没有返回任何参数,则该数组的值将为空字符串。 
 
             if (errPara != String.Empty) 
 
             { 
 
                 bld.Append("/r/nErr. Par.: ").Append(errPara); 
 
             } 
 
         } 
 
     } 
 

      MessageBox.Show(bld.ToString()); 
 
 } 
 

  //数据库说明:MyTest数据库,RWTest表,包含3列:ID(int),Description(varchar(50),ImgField(Image) 
 
         private void buttonFileToDB_Click(object sender, EventArgs e) 
 
         { 
 
             SqlConnection sqlConnection = new SqlConnection("Data Source = liuxueqin; Initial Catalog=MyTest;Integrated Security=True"); 
 
             SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("Select * from RWTest", sqlConnection); 
 
             SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter); 
 
             DataSet dataSet = new DataSet("RWTest"); 
 
             sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;//确定现有 DataSet 架构与传入数据不匹配时需要执行的操作。 
 
             String CurrentExeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; 
 
             string ImageFile = Path.GetDirectoryName(CurrentExeName) + ".//F1.jpg"; 
 
             FileStream fileStream = new FileStream(ImageFile, FileMode.OpenOrCreate, FileAccess.ReadWrite); 
 
             byte[] myData = new byte[fileStream.Length]; 
 
             fileStream.Read(myData, 0, System.Convert.ToInt32(fileStream.Length));//从流中读取字节块,并将数据写入到该缓冲区 
 
             fileStream.Close(); 
 
             try 
 
             { 
 
                 sqlDataAdapter.Fill(dataSet, "RWTest"); 
 
                 //DataRow表示DataTable中的一行数据 
 
                 System.Data.DataRow dataRow; 
 
                 dataRow = dataSet.Tables["RWTest"].NewRow(); 
 
                 //dataRow1["ID"] = 1; 
 
                 //dataRow1["Description"] = "This would be description text"; 
 
                 //dataRow1["ImgField"] = myData; 
 
                 dataSet.Tables["RWTest"].Rows.Add(dataRow); 
 
                 sqlDataAdapter.Update(dataSet, "RWTest"); 
 
                 sqlConnection.Close(); 
 
                 MessageBox.Show("写入数据库成功!", " 信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 
 
             } 
 
             catch (Exception ex) 
 
             { 
 
                 if (sqlConnection.State == ConnectionState.Open) 
 
                 { 
 
                     sqlConnection.Close(); 
 
                 } 
 
                 MessageBox.Show("写入数据库失败"+ex.Message, " 信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error); 
 
             } 
 
         } 
 

    

 

          private void buttonDBToFile_Click(object sender, EventArgs e) 
 
         { 
 
             SqlConnection sqlConnection = new SqlConnection("Data Source=liuxueqin;Initial Catalog=MyTest;Integrated Security=True"); 
 
             SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("Select * from RWTest", sqlConnection); 
 
             SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter); 
 
             DataSet dataSet = new DataSet("RWTest"); 
 

              byte[] MyData = new byte[0]; 
 
             sqlDataAdapter.Fill(dataSet, "RWTest"); 
 
             DataRow myRow; 
 
             myRow = dataSet.Tables["RWTest"].Rows[0]; 
 
             MyData = (byte[])myRow["imgField"]; 
 

              int ArraySize = MyData.GetUpperBound(0); 
 
             String CurrentExeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; 
 
             string ImageFile = System.IO.Path.GetDirectoryName(CurrentExeName) + ".//F2.jpg"; 
 
             FileStream fs = new FileStream(ImageFile, FileMode.OpenOrCreate, FileAccess.Write); 
 
             fs.Write(MyData, 0, ArraySize); 
 
             fs.Close(); 
 

              //---在界面上的2个textBox和1个pictureBox,用来显示从数据库中读出的ID,Description,ImageField字段 

 

              //textBoxGetID.Text = myRow["ID"].ToString(); 
 
            // textBoxGetDescription.Text = myRow["Description"].ToString(); 
 
             //pictureBoxGetImage.Image = Image.FromFile(ImageFile); 
 

               if (sqlConnection.State == ConnectionState.Open) 
 
             { 
 
                 sqlConnection.Close(); 
 
             } 
 
             MessageBox.Show(" 从数据库读出数据成功!", " 信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 
 
         }