Blog / Home
About
Media Gallery

Welcome
to
Thronic.com

ժʝ_

Databasegrensesnitt for SQL CE i C#


A static class for using SQL CE in a multi-threaded application.

Sample code:
using System;
using System.Data.SqlServerCe;
using System.IO;
using System.Windows.Forms;

namespace MyApp
{
	struct qParam
	{
		public string pString;
		public object pValue;

		public qParam(string s, object o)
		{
			pString = s;
			pValue = o;
		}
	}

	static class djDBI
	{
		private static SqlCeConnection DBC;
		private static SqlCeTransaction SqlTransaction;
		private static object DbLock = new object();

		public static void Open()
		{
			try {
				DBC = new SqlCeConnection(Form1.DBFileConStr);
				DBC.Open();

			} catch (Exception e) {
				// Handle exception. 
				// Handle other exceptions below in the calling code, or add your own.
			}
		}

		public static void PrepTransaction()
		{
			SqlTransaction = DBC.BeginTransaction();	
		}

		public static void CommitTransaction()
		{
			SqlTransaction.Commit();
		}

		public static void ExecuteNonQuery(string q, qParam[] p)
		{
			lock(DbLock) {
			using (SqlCeCommand DBQ = new SqlCeCommand(q, DBC)) {

				// Add any parameters received.
				foreach (qParam Param in p)
					DBQ.Parameters.AddWithValue(Param.pString, Param.pValue);	
				
				// Execute Update/Insert query.
				DBQ.ExecuteNonQuery();
			}}
		}

		public static SqlCeDataReader ExecuteQuery(string q, qParam[] p)
		{
			lock(DbLock) {
			using (SqlCeCommand DBQ = new SqlCeCommand(q, DBC)) {
				
				// Add any parameters received.
				foreach (qParam Param in p)
					DBQ.Parameters.AddWithValue(Param.pString, Param.pValue);

				// Execute Select query and return a reader.
				return DBQ.ExecuteReader();
			}}
		} 

		public static void Close()
		{
			try { DBC.Dispose(); } catch (Exception) {}
		}
	}
}

Making calls:
// UPDATE/INSERT queries with parameters.
djDBI.ExecuteNonQuery("INSERT INTO x WHERE [email protected] (...) VALUES (...,@boo)", new qParam[] {
	new qParam("@foo",somevar),
	new qParam("@boo",othervar)
});

// SELECT queries without parameters.
using (SqlCeDataReader r = djDBI.ExecuteQuery("SELECT * FROM x", new qParam[] {})) {
	while (r.Read())
		// Do something...
}



Original Post: Jan 27th, '22 20:19 CET.
Updated: Jan 27th, '22 20:22 CET.

SQL C#
π