40歳からのキャリアチェンジ

20代はエンジニア・PM、30代はWeb系エンジニア向けのキャリアアドバイザー。40代の今はフリーランスで開発含めて色々やってます。技術ネタとしてはRuby/RailsとJavaScript関連あたり

ADOの処理を自分好みにしてみた

データ抽出、加工のために個人的に作ったツールがあるんだけど、WSH(JScript)+ADOを使ってDB(Oracle)接続する処理をもっと使い勝手をよくしたいと思って長年勉強していたら、こんな感じのソースが書けるようになってきました。(配列やハッシュの扱いをRubyっぽく書けるようにprorotype.jsの力を借りています。WSHprototype.jsを使うには以前書いたWSH上でPrototype.jsを使って楽しようというエントリを参考にしてください)

//DBO.js
var DBO = Class.create({
  initialize:function(sql){
    this.sql = sql;
    this.objADO="";
    var config = new Config();
    this.udl_filepath = config.udl_filepath;
    this.objRS ="";
    this.connect();
    this.items = this.getItems();
  },
  connect:function(){
    var strConnection = 'File Name=' + this.udl_filepath;
    this.objADO = new ActiveXObject('ADODB.Connection');
    this.objADO.Open(strConnection);
    this.objRS = this.objADO.Execute(this.sql);
    return this.objRS;
  },
  close:function(){
  return this.objADO.Close();
  },
  setProperty:function(_obj){
    for(var i=0; i < this.objRS.Fields.Count;i++){
      var _property = this.objRS.Fields(i).name;
    _obj[_property.toLowerCase()] = this.objRS.Fields(i).value;
    }
  },
  getItems:function(){
    var items= [];
    var i = 0;
    while(!(this.objRS.EOF)) {
      var item = {};
      for(var j=0; j < this.objRS.Fields.Count;j++){
        /*
        SQL文のSELECT句に指定されているフィールド名を 
        このクラスのプロパティとして自動的に指定
        */
        var _property = this.objRS.Fields(j).name;
        item[_property.toLowerCase()]= this.objRS.Fields(j).value;
      }
    items[i] = item;
    i++;
    this.objRS.MoveNext();
    }
    return items;
  }
});
var Config = function(){
  this.base_filepath = 'C:\\home\\xxxxxx\\';
  this.sql_filepath = this.base_filepath + 'sql\\';
  this.text_filepath = this.base_filepath + 'text\\';
  this.img_filepath = this.base_filepath + 'img\\';
  this.cache_filepath = this.base_filepath + 'cache\\'; 
  this.page_filepath = this.base_filepath + 'page\\';
  this.log_filepath = this.base_filepath + 'log\\';
  this.udl_filepath = 'C:\\udl\\index.udl';
};

例えば、従業員情報を管理しているemployeeというテーブルがあった場合にはこんな感じのmodel らしきものを作っています

//Employee.js
var Employee = Class.create({
  initialize:function(){
    var _sql = "SELECT first_name, last_name, department_cd FROM employee where cd ='001'";
    var objDBO = new DBO(_sql);
    objDBO.setProperty(this);
  },
  getName:function(){
    return this.first_name + this.last_name;
  },
  getDepartmentName:function(){
    //
  }
  
});

あとはこんな感じで出来上がり

//main.wsf
<job>
<script language="javascript" src="dummy.js" />
<script language="javascript" src="prototype.js" />
<script language="javascript" src="DBO.js" />
<script language="javascript" src="Employee.js" />
<script language="javascript">
  //実際の処理
  var E = new Employee();
  WScript.Echo(E.getName());
</script>
</job>