ibatis && ibatisnet (續)

yellowlee發表於2009-01-14
2,ibatisnet
c#的和java的基本沒有太大區別,sqlMap寫法都是一樣的
使用的資料庫與java的一樣。
貼出程式碼。

Maps.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace MapUpdate
{
    class Maps
    {
        private int _id;
        public int id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _eName;
        public string eName
        {
            get { return _eName; }
            set { _eName = value; }
        }

        private string _imageName;
        public string imageName
        {
            get { return _imageName; }
            set { _imageName = value; }
        }

        private int _xmin;
        public int xmin
        {
            get { return _xmin; }
            set { _xmin = value; }
        }

        private int _ymin;
        public int ymin
        {
            get { return _ymin; }
            set { _ymin = value; }
        }

        private int _xmax;
        public int xmax
        {
            get { return _xmax; }
            set { _xmax = value; }
        }

        private int _ymax;
        public int ymax
        {
            get { return _ymax; }
            set { _ymax = value; }
        }

        private string _scale;
        public string scale
        {
            get { return _scale; }
            set { _scale = value; }
        }

        private string _valid;
        public string valid
        {
            get { return _valid; }
            set { _valid = value; }
        }
    }
}

FileControl.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data;
using System.Xml;
using log4net;

namespace MapUpdate
{
    class FileControl
    {
        #region common define
        private int total = 0;
        //private int FileNumber = 0;
        private StreamWriter sw1;
        private StreamReader sr1;
        private string FileName;
        private string TextString;
        private static string DEFAULT_PATH = "\\\\192.168.7.44\\數字地圖";//"\\\\172.27.1.199\\數字地圖";
        #endregion

        private string appPath = Application.ExecutablePath + ".config";
        private XmlDocument configData = new XmlDocument();
        ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        ///
        /// GetAppValue(String Key)
        ///

        ///
        ///
        public string GetAppValue(string key)
        {
            return configData.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value;
        }

        ///
        /// 預設根目錄
        ///

        /// DEFAULT_PATH
        public string getDefaultPath()
        {
            return DEFAULT_PATH;
        }

        ///
        /// 獲得總檔案數
        ///

        ///
        public int getTotal()
        {
            return this.total;
        }

        ///
        /// 設定檔名
        ///

        ///
        public void SetFileName(string str)
        {
            this.FileName = str;
        }

        ///
        /// 開啟檔案
        ///

        public void OpenFile()
        {
            if (File.Exists(FileName))
            {
                sw1 = File.AppendText(FileName);
            }
            else
            {
                sw1 = File.CreateText(FileName);

            }
        }

        ///
        /// 刪除檔案
        ///

        public void DeleteFile()
        {
            if (File.Exists(FileName))
            {
                File.Delete(FileName);
            }
        }

        ///
        /// 讀取檔案
        ///

        public void ReadFile()
        {
            if (File.Exists(FileName))
            {
                try
                {
                    sr1 = File.OpenText(FileName);
                }
                catch (Exception ex)
                {
                    //DebugLog.WriteLog(ex);
                    log.Debug(ex);
                }

            }
            else
            {
                //DebugLog.Debuglog("檔案不存在");
                log.Debug("檔案不存在");
            }
        }

        ///
        /// 按行讀取檔案
        ///

        ///
        public string ReadFileByLine()
        {
            TextString = sr1.ReadLine();
            return this.TextString;
        }

        ///
        /// 寫字串到檔案
        ///

        ///
        public void WriteFile(string str)
        {
            if (File.Exists(FileName))
            {
                sw1.WriteLine(str);
            }

            else
            {
                sw1 = File.CreateText(FileName);
                sw1.WriteLine(str);
            }
        }

        ///
        /// 寫object型別到檔案
        ///

        ///
        public void WriteFile(object obj)
        {
            if (File.Exists(FileName))
            {
                sw1.WriteLine(obj.ToString());
            }

            else
            {
                sw1 = File.CreateText(FileName);
                sw1.WriteLine(obj.ToString());
            }
        }

        ///
        /// 關閉檔案
        ///

        public void CloseFile()
        {
            sw1.Close();
        }

        ///
        /// 關閉reader
        ///

        public void CloseReader()
        {
            try
            {
                sr1.Close();
            }
            catch (Exception ex)
            {
                //DebugLog.WriteLog(ex);
                log.Debug(ex.Message);
            }
        }

        ///
        /// 拷貝目錄
        ///

        ///
        ///
        ///
        public void CopyDirectory(string sourceDirName, string destDirName, string pipei)
        {
            FileControl fc = new FileControl();
            fc.SetFileName(Environment.CurrentDirectory + "\\path.txt");
            fc.OpenFile();

            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            if (destDirName[destDirName.Length - 1] != Path.DirectorySeparatorChar)
                destDirName = destDirName + Path.DirectorySeparatorChar;

            string[] files = Directory.GetFiles(@sourceDirName, pipei);
            foreach (string file in files)
            {
                File.Copy(file, destDirName + Path.GetFileName(file), true);

                fc.WriteFile(destDirName + Path.GetFileName(file));
                File.SetAttributes(destDirName + Path.GetFileName(file), FileAttributes.Normal);
                total++;
            }

            fc.CloseFile();
            string[] dirs = Directory.GetDirectories(sourceDirName);
            foreach (string dir in dirs)
            {
                CopyDirectory(dir, destDirName + Path.GetFileName(dir), pipei);
            }

            //return total;
        }

        ///
        /// 生成給定的路徑下的檔案路徑
        ///

        ///
        ///
        ///
        public void GenerateFilePath(string sourceDirName, string pipei, string indexFile)
        {
            FileControl fc = new FileControl();
            fc.SetFileName(Environment.CurrentDirectory + "\\" + indexFile);
            fc.OpenFile();

            string[] files = Directory.GetFiles(@sourceDirName, pipei);
            foreach (string file in files)
            {
                if (sourceDirName.LastIndexOf("\\") != sourceDirName.Length - 1)
                {
                    fc.WriteFile(sourceDirName + "\\" + Path.GetFileName(file));
                }
                else
                {
                    fc.WriteFile(sourceDirName + Path.GetFileName(file));
                }
                total++;
            }
            fc.CloseFile();
        }

        ///
        /// 先取出所有初步篩選的檔案路徑,然後在路徑中搜尋檔案,按檔案路徑直接複製
        /// 第一步,生成一個存放檔案路徑的檔案
        ///

        ///
        ///
        ///
        ///
        public void GenerateCopyPath(string sourceDirName, string destDirName, string pipei, string indexFile)
        {
            FileControl fc = new FileControl();
            fc.SetFileName(Environment.CurrentDirectory + "\\" + indexFile);
            fc.OpenFile();

            //  if (!Directory.Exists(destDirName))
            // {
            //     Directory.CreateDirectory(destDirName);
            // }

            //if (destDirName[destDirName.Length - 1] != Path.DirectorySeparatorChar)
            //    destDirName = destDirName + Path.DirectorySeparatorChar;

            string[] files = Directory.GetFiles(@sourceDirName, pipei);
            foreach (string file in files)
            {
                if (sourceDirName.LastIndexOf("\\") != sourceDirName.Length - 1)
                {
                    fc.WriteFile(sourceDirName + "\\" + Path.GetFileName(file));
                }
                else
                {
                    fc.WriteFile(sourceDirName + Path.GetFileName(file));
                }
                //File.SetAttributes(destDirName + Path.GetFileName(file), FileAttributes.Normal);
                total++;
            }

            fc.CloseFile();
            string[] dirs = Directory.GetDirectories(sourceDirName);
            foreach (string dir in dirs)
            {
                GenerateCopyPath(dir, destDirName + Path.GetFileName(dir), pipei, indexFile);
            }
        }

        ///
        /// 從完整路徑名中獲得檔名
        ///

        ///
        ///
        public string getFileNameFromPath(string path)
        {
            string temp = path;
            int num = temp.LastIndexOf("\\");
            temp = path.Substring(num + 1);
            return temp;
        }

        ///
        /// 從完整路徑名中獲得除去檔名的路徑
        ///

        ///
        ///
        public string getFilePathFromPath(string path)
        {
            string temp = path;
            int num = temp.LastIndexOf("\\");
            temp = temp.Substring(0, num);
            return temp;
        }

        ///
        /// 第二步,開始拷貝,從檔案裡面的路徑查詢是否存在需要的檔案,拷貝
        ///

        ///
        ///
        ///
        ///
        ///
        //public void MutiCopyPath(string sourceDirName, string destDirName, string pipei, string fileNamePathAll, string pipeiFilePathAll)
        //{
        //    DBFactory dbf = new DBFactory();
        //    DataSet ds = new DataSet();
        //    DataTable dt = new DataTable();
        //    DataTable dt1 = new DataTable();
        //    OleDbDataReader dr;

        //    string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Environment.CurrentDirectory + "\\" + ";Extended Properties=\"Text;HDR=yes;FMT=Delimited;\";";
        //    OleDbConnection con = new System.Data.OleDb.OleDbConnection(connStr);
        //    con.Open();
        //    //有匹配規則內容的檔案
        //    string pipeiFileName = getFileNameFromPath(pipeiFilePathAll);
        //    string pipeiFilePath = getFilePathFromPath(pipeiFilePathAll);
        //    FileStream fs = new FileStream(Environment.CurrentDirectory + "\\out.txt", FileMode.Append, FileAccess.Write);
        //    StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Unicode);
        //    //所有路徑存放的檔案
        //    string fileName = getFileNameFromPath(fileNamePathAll);
        //    string fileNamePath = getFilePathFromPath(fileNamePathAll);

        //    string sql = "select * from " + fileName;


        //    string sql1 = "select * from " + pipeiFileName;

        //    OleDbDataAdapter adapter = new OleDbDataAdapter(sql, con);
        //    adapter.Fill(ds, "text1");
        //    int i = ds.Tables["text1"].Rows.Count;

        //    OleDbDataAdapter adapter1 = new OleDbDataAdapter(sql1, con);
        //    adapter1.Fill(ds, "text2");
        //    int j = ds.Tables["text2"].Rows.Count;


        //    string sql2 = "select a.path from " + fileName + " a where a.path like '*" + pipeiFileName + "*'";
        //    //string sql3 = "select * from " + fileName;
        //    OleDbCommand comm = new OleDbCommand(sql2, con);
        //    try
        //    {
        //        int recordNumbers = comm.ExecuteNonQuery();
        //        dr = comm.ExecuteReader();
        //        int recs = 1;
        //        while (dr.Read())
        //        {

        //            //dr.GetValue(1);
        //            //sw.WriteLine(dr.GetString(0). + "  " + recs);
        //            string ss = dr.GetValue(0).ToString();
        //            //DebugLog.WriteLog(dr.GetValue(0)+"  "+recs);
        //            recs++;
        //        }
        //        dr.Close();
        //        if (recordNumbers != 0)
        //        {
        //            DebugLog.WriteLog("ok!");
        //        }
        //        comm.Dispose();
        //        sw.Close();
        //        fs.Close();
        //    }
        //    catch (Exception ex)
        //    {
        //        //DebugLog.Debuglog(ex);
        //        log.Debug(ex.Message());
        //        comm.Dispose();
        //        sw.Close();
        //        fs.Close();
        //    }

        //}

        ///
        /// 第二步的第二種方法:直接用字串匹配來找路徑
        ///

        ///
        ///
        ///
        public void MutiCopyPath(string pipei, string oraPath, string tarPath)
        {
            string pipeiStr = pipei;            //匹配的字串
            string raPathStr = oraPath;        //路徑
            string tarPathStr = tarPath;        //路徑
            //string indexPathStr = indexPath;    //檔名  預設index.txt
            string indexFileName = "index.txt";

            StreamReader sr1 = new StreamReader(Environment.CurrentDirectory + "\\" + indexFileName);
            //ArrayList al = new ArrayList ();
            string sr1Str;

            while ((sr1Str = sr1.ReadLine()) != null)
            {
                string fileName = sr1Str;
                int num = sr1Str.LastIndexOf("\\");
                fileName = fileName.Substring(num + 1);

                string sr1Temp = sr1Str;
                int numTemp = sr1Str.LastIndexOf("\\");
                sr1Temp = sr1Temp.Substring(numTemp + 1);


                if (pipeiStr != "" && sr1Str != "")
                {
                    try
                    {
                        if (sr1Temp.LastIndexOf(pipeiStr) >= 0)
                        {
                            //string files = Directory.GetFiles(sr1Str);
                            File.Copy(sr1Str, tarPathStr + "\\" + fileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        //DebugLog.WriteLog(ex);
                        log.Debug(ex.Message);
                    }
                }

            }

        }

        ///
        /// 獲得資料夾內的檔案總數
        ///

        ///
        ///
        public static int GetFilesCount(System.IO.DirectoryInfo dirInfo)
        {
            int totalFile = 0;
            totalFile += dirInfo.GetFiles().Length;
            foreach (System.IO.DirectoryInfo subdir in dirInfo.GetDirectories())
            {
                totalFile += GetFilesCount(subdir);
            }
            return totalFile;
        }
    }

}

provider.config 資料庫驅動

xmlns="http://ibatis.apache.org/providers"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 
          name="sqlServer2.0"
        enabled="true"
        description="Microsoft SQL Server, provider V2.0.0.0 in framework .NET V2.0"
        assemblyName="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
        connectionClass="System.Data.SqlClient.SqlConnection"
        commandClass="System.Data.SqlClient.SqlCommand"
        parameterClass="System.Data.SqlClient.SqlParameter"
        parameterDbTypeClass="System.Data.SqlDbType"
        parameterDbTypeProperty="SqlDbType"
        dataAdapterClass="System.Data.SqlClient.SqlDataAdapter"
        commandBuilderClass=" System.Data.SqlClient.SqlCommandBuilder"
        usePositionalParameters = "false"
        useParameterPrefixInSql = "true"
        useParameterPrefixInParameter = "true"
        parameterPrefix="@"
        allowMARS="false"
    />

   name="oracleClient1.0"
 description="Oracle, Microsoft provider V1.0.5000.0"
 enabled="true"
 assemblyName="System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" connectionClass="System.Data.OracleClient.OracleConnection"
 commandClass="System.Data.OracleClient.OracleCommand"
 parameterClass="System.Data.OracleClient.OracleParameter"
 parameterDbTypeClass="System.Data.OracleClient.OracleType"
 parameterDbTypeProperty="OracleType"
 dataAdapterClass="System.Data.OracleClient.OracleDataAdapter"
 commandBuilderClass="System.Data.OracleClient.OracleCommandBuilder"
 usePositionalParameters="false"
 useParameterPrefixInSql="true"
 useParameterPrefixInParameter="false"
 parameterPrefix=":"
 allowMARS="false"   
  />
 


SqlMap.config



  <!--
   
    --&gt

 

  <!-- Data Source --&gt

 
   
   
 

  <!--
 
   
   
   
   
   
 
 

--&gt
  <!-- Sql Map files  --&gt
 
   
 





Maps.xml



 

    <!-- 測試:for oracle --&gt
   

    <!-- 測試:for sqlserver2000 --&gt
   


    <!-- 找出當前表內id的最大值 --&gt
   

    <!-- 初始化,刪除現有記錄 --&gt
   
      delete from mapsall06
   


    <!-- 測試: insert use map--&gt
   
        insert into mapsall06
      (id, eName, imageName, xmin, ymin, xmax, ymax, scale, valid)
    values
      (#id#,
       #eName#,
       #imageName#,
       #xmin#,
       #ymin#,
       #xmax#,
       #ymax#,
       #scale#,
       #valid#)
   


    <!-- 插入圖形資訊 --&gt
   
    insert into mapsall06
      (id, eName, imageName, xmin, ymin, xmax, ymax, scale, valid)
    values
      (#id#,
       #eName#,
       #imageName#,
       #xmin#,
       #ymin#,
       #xmax#,
       #ymax#,
       #scale#,
       #valid#)
   


    <!-- 更新比例尺欄位,去掉\new --&gt
   
          update mapsall06
       set scale = replace(scale, '\new', '')
     where length(scale) > 4
   ]]>
   


    <!-- 將有對應新圖的舊圖的valid值置為2 for oracle9i or sqlserver2000--&gt
   
           UPDATE mapsall06
        SET valid = '2'
      WHERE (id IN (SELECT id
                      FROM (SELECT eName, MIN(id) AS id
                              FROM mapsall06
                             GROUP BY eName
                            HAVING COUNT(*) > 1) DERIVEDTBL))
                            ]]>

   



   
    select id, xmin, ymin, xmax, ymax, scale, valid
          from mapsall06
         where scale = #scale#
           and valid = #valid#
   


   

   
    update mapsall06 set valid='0'
        where id = #id#
        and valid = '1'
   


   
          update mapsall06 set valid = #in_valid#
        where xmin >= #xmin#
        and ymin >= #ymin#
        and xmax <= #xmax#
        and ymax <= #ymax#
        and scale = #scale#
        and valid = #valid#
    ]]>
   


   
          update mapsall06 set valid = '0'
        where id = #id#
        and valid <> '2'
    ]]>
   


   
    update mapsall06 set valid = '0'
        where valid = '3'
   


 



app.config  主要是log4net的配置,由於c#的簡易log和console與java的一樣
這裡使用log4net,以免重複。


 
   

 

 
 

 
    <!--定義輸出到檔案中--&gt
   
      <!--定義檔案存放位置--&gt
     
     
     
     
     
        <!--每條日誌末尾的文字說明--&gt
       

        <!--輸出格式--&gt
        <!--樣例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info--&gt
       
     

   

    <!--定義輸出到控制檯命令列中--&gt
   
     
       
     

   

    <!--定義輸出到windows事件中--&gt
   
     
       
     

   

    <!--定義輸出到資料庫中,這裡舉例輸出到Access資料庫中,資料庫為C盤的log4net.mdb--&gt
   
     
     
     
      <!--定義各個引數--&gt
     
       
       
       
       
         
       

     

     
       
       
       
       
         
       

     

     
       
       
       
       
         
       

     

     
       
       
       
       
         
       

     

     
       
       
       
       
         
       

     

   

   
    <!--定義日誌的輸出媒介,下面定義日誌以四種方式輸出。也可以下面的按照一種型別或其他型別輸出。--&gt
   
      <!--檔案形式記錄日誌--&gt
     
      <!--控制檯控制顯示日誌--&gt
     
      <!--Windows事件日誌--&gt
     
      <!-- 如果不啟用相應的日誌記錄,可以通過這種方式註釋掉
     
      --&gt
   


 




使用log4net注意在assemblyInfo.cs後面加上一行
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

MapsUpdate.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using log4net;
using IBatisNet.Common;
using IBatisNet.DataMapper;
using System.Reflection;
using IBatisNet.DataMapper.Configuration;
using System.IO;

namespace MapUpdate
{
    class MapsUpdate
    {
        #region define
        public int id = 0;
        public int x1 = 0;
        public int x2 = 0;
        public int y1 = 0;
        public int y2 = 0;
        public string scale = "";
        public string valid = "";
        public static string[] mapPath = { "500", "1000", "2000", "500\\new", "1000\\new", "2000\\new" };
        ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);       
        #endregion

        ///
        ///
        ///

        public MapsUpdate()
        {
            Test();
        }

        ///
        /// 測試
        ///

        public void Test()
        {
            //doGenFilePath();
            //doInit();
            //doMapInsert();
            //doMapScaleupdate();
            doMapUpdate();
        }

        ///
        /// 初始化,清空資料庫(檢測連線)
        ///

        public void doInit()
        {
            DomSqlMapBuilder builder = new DomSqlMapBuilder();
            ISqlMapper sqlMap = builder.Configure("SqlMap.config");
            try
            {
                sqlMap.BeginTransaction();
                //sqlMap.OpenConnection();
                //Maps map = new Maps();
        

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16179598/viewspace-539593/,如需轉載,請註明出處,否則將追究法律責任。

相關文章