Welcome

首页 / 软件开发 / .NET编程技术 / .NET Compact Framework下SQL CE的使用

.NET Compact Framework下SQL CE的使用2011-08-20 博客园 Jake.NET在Wince和Windows Mobile下最常用的数据库为SQL CE,SQL CE也曾经叫做SQL Server for Windows CE和SQL Server

Mobile Edition,最新版本命名为SQL Server Compact 3.5 SP1。 SQL Server Compact不仅仅能运 行于Wince和Windows Mobile,而且能运行于Windows的PC上,是Access的有效替代品,如果不使用存储 过程,在SQL Server Compact下开发的程序几乎可以无修改移植到SQL Server的其他服务器版本上。可 以参见这篇文章 SQL Server Express和SQL Server Compact的应用 。在这篇文章中我会使用SQL CE 这一命名。

在.NET Compact Framework下进行SQL CE使用和开发,需要应用库System.Data.SqlServerCe.dll, 需要注意的是不同的SQL CE版本使用不用的DLL版本. SQL CE 3.5的库一般对应以下的目录 C:Program FilesMicrosoft SQL Server Compact Editionv3.5 ADO.net DLL,而SQL CE 3.0的库一般对应以下的 目录 C:Program FilesMicrosoft Visual Studio 8SmartDevicesSDKSQL ServerMobile,彼此不 相兼容。由于开发的命名空间(namespace)是一致的,所以开发的程序可以用在不用的SQL CE版本。

helper类

下面演示的是一个SQL CE的helper类,这个类只是针对SQL CE数据库,没有考虑移植到其他数据库, 所以所有的类都使用SQL CE相关的类。

class SqlCeHelper : IDisposable
{
private SqlCeConnection connection;
private SqlCeCommand command;
private const string connectionString = "Data Source=/DB/db.sdf";

#region Open/Close
public void Open()
{
try
{
connection = new SqlCeConnection (connectionString);
command = connection.CreateCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;

connection.Open();
}
catch (DataException e)
{
Console.WriteLine(e.Message);
}
}

public void Close()
{
connection.Close();
connection.Dispose();
}

public void Dispose()
{
connection.Close();
connection.Dispose();
command.Dispose();
}
#endregion

#region Operatons
public SqlCeDataReader ExecuteReader(string sql)
{
command.CommandText = sql;
SqlCeDataReader reader = null;
try
{
reader = command.ExecuteReader();
}
catch (DataException e)
{
Console.WriteLine(e.Message);
}
return reader;
}

public DataSet ExecuteDataSet(string sql)
{
command.CommandText = sql;
SqlCeDataAdapter adapter = new SqlCeDataAdapter (command);
DataSet ds = new DataSet(); ;

try
{
adapter.Fill(ds);
}
catch (DataException e)
{
Console.WriteLine(e.Message);
}
return ds;
}

public int ExecuteNonQuery(string sql)
{
command.CommandText = sql;
int result = -1;

try
{
result = command.ExecuteNonQuery();
}
catch (DataException e)
{
Console.WriteLine(e.Message);

}
return result;
}

public object ExecuteScalar(string sql)
{
command.CommandText = sql;
object o = null;
try
{
o = command.ExecuteScalar();
}
catch (DataException e)
{
Console.WriteLine(e.Message);
}
return o;
}
#endregion

#region Transaction
public void BeginTransaction()
{
command.Transaction = connection.BeginTransaction();
}

public void CommitTransaction()
{
command.Transaction.Commit();
}

public void RollbackTransaction()
{
command.Transaction.Rollback();
}
#endregion
}