License Public Domain
Lines 26
Keywords
Database (1) .Net (8) SqlClient (1)
Included in this Library
Permissions
Group Owner: .Net
Viewable by Everyone
Editable by Spencer Ruport
Hide
Easily highlight source code for your blog with our Syntax Highlighter. Join Siafoo Now or Learn More

SQL Access Encapsulation Atom Feed 1

In Brief I wrote this (very simple) wrapper to significantly reduce the number of lines in my code that perform database operations.
# 's
 1public class DataSourceConnection
2{
3 private SqlConnection conn;
4 private SqlCommand comm;
5 private SqlDataReader dr;
6
7 public DataSourceConnection(string ProcedureName, string DSN)
8 {
9 conn = new SqlConnection(DSN);
10 conn.Open();
11 comm = new SqlCommand(ProcedureName, conn);
12 comm.CommandType = CommandType.StoredProcedure;
13 }
14
15 public void ExecuteNonQuery() { if (dr != null) dr.Close(); comm.ExecuteNonQuery(); }
16 public void ExecuteScalar() { if (dr != null) dr.Close(); comm.ExecuteScalar(); }
17 public void ExecuteReader() { if (dr != null) dr.Close(); dr = comm.ExecuteReader(); }
18
19 public void AddParameter(string Name, object value)
20 {
21 comm.Parameters.AddWithValue(Name, value);
22 }
23 public object this[string index] { get { return dr[index]; } }
24 public bool Read() { return dr.Read(); }
25 public void Close() { conn.Close(); }
26
27 public SqlConnection Connection { get { return conn; } }
28 public SqlCommand Command { get { return comm; } }
29 public SqlDataReader DataReader { get { return dr; } }
30}

I wrote this (very simple) wrapper to significantly reduce the number of lines in my code that perform database operations.

Comments

over 9 years ago (07 Oct 2008 at 10:00 PM) by Stou S.
Does the AddWithValue call sanitize the database input to prevent SQL Injection (http://xkcd.com/327/)?
over 8 years ago (12 Oct 2009 at 05:08 PM) by warleggon
I've tried implementing this class in a project, and can get a connection, but when I try to implement a command, I get an error saying that the sql command can't be found. Can you show an example of executing a sql command using this class?