// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace E { public class T1 { public int F1 { get; set; } public string F2 { get; set; } } public class DBException : Exception { public DBException(Exception ex) : base("Implementation specific exception", ex) { } } public interface IT1DB { IList GetAll(); T1 GetOne(int f1); void AddOne(T1 o); void DeleteOne(T1 o); } public class T1SQLServer : IT1DB { private string constr; public T1SQLServer(string constr) { this.constr = constr; } public IList GetAll() { try { List res = new List(); using(SqlConnection con = new SqlConnection(constr)) { con.Open(); using(SqlCommand cmd = new SqlCommand("SELECT f1,f2 FROM t1", con)) { using(SqlDataReader rdr = cmd.ExecuteReader()) { while(rdr.Read()) { res.Add(new T1 { F1 = (int)rdr[0], F2 = (string)rdr[1] }); } } } } return res; } catch (SqlException ex) { throw new DBException(ex); } } public T1 GetOne(int f1) { try { T1 res = null; using(SqlConnection con = new SqlConnection(constr)) { con.Open(); using(SqlCommand cmd = new SqlCommand("SELECT f1,f2 FROM t1 WHERE f1 = @f1", con)) { cmd.Parameters.Add("@f1", SqlDbType.Int); cmd.Parameters["@f1"].Value = f1; using(SqlDataReader rdr = cmd.ExecuteReader()) { if(rdr.Read()) { res = new T1 { F1 = (int)rdr[0], F2 = (string)rdr[1] }; } } } } return res; } catch (SqlException ex) { throw new DBException(ex); } } public void AddOne(T1 o) { try { using(SqlConnection con = new SqlConnection(constr)) { con.Open(); using(SqlCommand cmd = new SqlCommand("INSERT INTO t1(f1,f2) VALUES(@f1,@f2)", con)) { cmd.Parameters.Add("@f1", SqlDbType.Int); cmd.Parameters.Add("@f2", SqlDbType.VarChar, 50); cmd.Parameters["@f1"].Value = o.F1; cmd.Parameters["@f2"].Value = o.F2; cmd.ExecuteNonQuery(); } } } catch (SqlException ex) { throw new DBException(ex); } } public void DeleteOne(T1 o) { try { using(SqlConnection con = new SqlConnection(constr)) { con.Open(); using(SqlCommand cmd = new SqlCommand("DELETE FROM t1 WHERE f1 = @f1", con)) { cmd.Parameters.Add("@f1", SqlDbType.Int); cmd.Parameters["@f1"].Value = o.F1; cmd.ExecuteNonQuery(); } } } catch (SqlException ex) { throw new DBException(ex); } } } public class Program { public static void Main(string[] args) { try { IT1DB db = new T1SQLServer(@"Server=ARNEPC3\SQLEXPRESS;Database=Test;Integrated Security=SSPI"); T1 o = db.GetOne(2); Console.WriteLine(o.F2); foreach(T1 r in db.GetAll()) { Console.WriteLine(r.F2); } T1 z = new T1 { F1 = 77, F2 = "ZZZZ" }; db.AddOne(z); foreach(T1 r in db.GetAll()) { Console.WriteLine(r.F2); } db.DeleteOne(z); foreach(T1 r in db.GetAll()) { Console.WriteLine(r.F2); } } catch (DBException ex) { Console.WriteLine(ex.Message + " -> " + ex.InnerException.Message); } } } }