Tuesday, 30 December 2008

Using Spring.NET to load data to DataTable

public class Program
{
  static void Main(string[] args)
  {
    IDbProvider provider = new DbPath("server", "database").DbProvider;
    TestDao dao = new TestDao(provider);
    DataTable dt = dao.Select();
    foreach(DataRow row in dt.Rows)
    {
      Console.WriteLine(string.Format("{0}: {1}",row["Id"],row["Name"]));
    }
    Console.ReadLine();
  }
}
class DbPath
{
  private const string connectionString = @"Persist Security Info=False; Integrated Security=SSPI;
    Server={0}; Database={1}; Connect Timeout={2}";
      
  private readonly string server;
  private readonly string database;
  private int timeout = 30;
      
  public DbPath(string server, string database)
  {
    this.server = server;
    this.database = database;
  }
  
  public string ConnectionString
  {
    get { return string.Format(connectionString,server,database,timeout); }
  }
  public IDbProvider DbProvider
  {
    get
    {
      IDbProvider dbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
      dbProvider.ConnectionString = ConnectionString;
      return dbProvider;
    }
  }
}
        
class TestDao : AdoDaoSupport
{
  private readonly string selectAllSql = @"SELECT Id, Name FROM Table1";
  public TestDao(IDbProvider dbProvider)
  {
    this.DbProvider = dbProvider;
  }
  public DataTable Select()
  {
    return AdoTemplate.DataTableCreate(CommandType.Text, selectAllSql);
  }
} 
class TestUpdateDao : AdoDaoSupport
{
  private readonly string deleteSql = @"DELETE FROM Table1 WHERE Id = @Id";
  public TestUpdateDao(IDbProvider dbProvider)
  {
    this.DbProvider = dbProvider;
  }
  public void delete(int id)
  {
    IDbParameters parameters = CreateDbParameters();
    parameters.Add("Id", DbType.Int32).Value = id;
    AdoTemplate.ExecuteNonQuery(CommandType.Text, deleteSql, parameters);
  }
} 

No comments:

Post a Comment