c#---通过xml读取数据库

23 篇文章 0 订阅

SectorList 是自己写的类

xml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;

namespace Xml
{
    //使用模板方法Template Method Pattern
    public class XML : IDisposable
    {
        private string configFilePath;  //Debug目录
        private XmlDocument xmlDoc;

        public XmlDocument XmlDoc
        {
            get { return xmlDoc; }
            set { xmlDoc = value; }
        }

        public XML(string cFPath)
        {
            this.configFilePath = cFPath;
            xmlDoc = new XmlDocument();
            xmlDoc.Load(this.configFilePath);
        }

        public void Dispose()
        {
            xmlDoc = null;
        }

        /***获取数据库配置信息*/
        public bool getDBInfo(string ndname, out string dbname, out string server, out string user, out string password)
        {
            bool result = true;
            dbname = "";
            server = "";
            user = "";
            password = "";

            XmlNodeList xnList = xmlDoc.SelectSingleNode(ndname).ChildNodes;
            foreach (XmlNode node in xnList)
            {
                if (node.Name == "dbName")
                    dbname = node.InnerText.Trim();
                if (node.Name == "server")
                    server = node.InnerText.Trim();
                if (node.Name == "user")
                    user = node.InnerText.Trim();
                if (node.Name == "password")
                    password = node.InnerText.Trim();
            }
            if (dbname == "" || server == "" || user == "" || password == "") result = false;
            return result;
        }

        /*获取Sql语句*/
        public bool getSqlCommand(string ndname, out string sqlcommand)
        {
            return getString(ndname, out sqlcommand);
        }

        public bool getString(string ndname, out string outstring)
        {
            bool result = true;
            outstring = "";
            XmlNode xn = xmlDoc.SelectSingleNode(ndname);
            outstring = xn.InnerText;
            if (outstring == "")
                result = false;
            return result;
        }

        public bool setItemInnerText(string ndname, string text)
        {
            bool result = true;
            try
            {
                XmlElement node = (XmlElement)xmlDoc.SelectSingleNode(ndname);
                node.InnerText = text;
                xmlDoc.Save(configFilePath);
            }
            catch (Exception e)
            {
                result = false;
                return result;
            }
            return result;
        }
    }

}

db.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using System.Data;
using Xml;

namespace DataBase
{
    public class DB
    {
        private string xmlNode;
        public DB(string xn)
        {
            xmlNode = xn;
        }
        private string dbname;
        private string server;
        private string user;
        private string pwd;

        private SqlConnection conn;

        /*初始化DataBase:从配置文件获取DataBase的配置信息*/
        public bool initialize(XML xml)
        {
            bool result = true;
            try
            {
                result = xml.getDBInfo(xmlNode, out this.dbname, out this.server, out this.user, out this.pwd);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }
            return result;
        }

        /*根据数据库的配置信息,构造连接字符串*/
        public string constructConnectionString()
        {
            string connStr = "";
            try
            {
                if (server == "localhost" && user == "null" && pwd == "null")
                    connStr = "data source=(local);integrated security=SSPI;initial catalog=" + dbname + ";Max Pool Size = 1024";
                else if (server != "localhost" && user == "null" && pwd == "null")
                    connStr = "data source=" + server + ";integrated security=SSPI;initial catalog=" + dbname + ";Max Pool Size = 1024";
                else if (server == "localhost" && user != "null" && pwd != "null")
                    connStr = "data source=(local);user id=" + user + ";password =" + pwd + ";initial catalog=" + dbname + ";Max Pool Size = 1024";
                else if (server != "localhost" && user != "null" && pwd != "null")
                    connStr = "data source=" + server + ";user id=" + user + ";password =" + pwd + ";initial catalog=" + dbname + ";Max Pool Size = 1024";

                return connStr;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }
        }

        /*连接数据库,返回SqlConnection*/
        public SqlConnection GetConnection()
        {
            try
            {
                string connStr = constructConnectionString();
                conn = new SqlConnection(connStr);
                conn.Open();
                return conn;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw e;
            }
        }

        /*选择操作,返回SqlDataReader*/
        public SqlDataReader selectR(string sqlSelect)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = sqlSelect;
                cmd.CommandTimeout = 5000000;
                cmd.Connection = conn;
                SqlDataReader reader = cmd.ExecuteReader();
                return reader;
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }

        //这里需要考虑selectR()返回的为null的情况
        public bool selectS(string sqlSelect, out string result)
        {
            SqlDataReader reader = selectR(sqlSelect);
            result = "";
            bool flag = false;

            if (reader.Read())
            {
                if (reader.IsDBNull(0) != true)
                {
                    result = System.Convert.ToString(reader.GetValue(0));
                    flag = true;
                }
                else
                    result = "null";
            }
            reader.Close();
            return flag;
        }

        public bool insert(string sqlInsert)
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = sqlInsert;
                cmd.CommandTimeout = 5000000;
                cmd.Connection = conn;
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                return true;
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
        }

        /*关闭数据库连接*/
        public void close()
        {
            try
            {
                conn.Close();
                conn.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw e;
            }
        }
    }
}

应用—EA.cs

        //数据的预处理
        private void prepareData(string configFile)
        {
            XML xml = new XML(configFile);
            DB db = new DB("Configuration/Database");
            try
            {
                #region ;从 配置文件 获取 数据库配置信息 ;并连接数据库
                if (db.initialize(xml) == false)
                {
                    Console.WriteLine("初始化配置文件错误!");
                    return;
                }
                if (db.GetConnection() == null)
                {
                    Console.WriteLine("连接数据库错误!");
                    return;
                }
                #endregion

                sList = new SectorList("Configuration/SqlInitSectorInfoTest37900");

                #region ;从 配置文件 获取 小区列表 各项信息;
                if (sList.initializeSectorInfo(db, xml) == false)
                    return;
                #endregion

            }
            catch (Exception e)
            {
                Console.WriteLine("PREPARE ERR: {0}!", e.Message);
            }
            finally
            {
                db.close();
                xml.Dispose();
            }
        }

EA.cs中的调用:DataPre.cs

/* 小区集合信息类 */
    public class SectorList
    {
        public List<Sector> sectorList;//小区个体对象数组
        public double[,] InterfMatrix;//小区间干扰信息矩阵

        #region XML文件属性
        private string xmlNodeSectorInfo;//初始化小区信息
        #endregion

        public SectorList(string xnSectorInfo)
        {
            xmlNodeSectorInfo = xnSectorInfo;
            sectorList = new List<Sector>();
        }

        /*从 数据库 获取 小区基础信息, 并创建 小区对象数组*/
        private bool initializeSectorInfo(DB db, XML xml)
        {
            string sqlInitSectorInfo;
            xml.getSqlCommand(xmlNodeSectorInfo, out sqlInitSectorInfo);

            SqlDataReader reader;
            reader = db.selectR(sqlInitSectorInfo);
            while (reader.Read())
            {
                if (reader.GetDouble(3) - 0 < 1e-7 || reader.GetDouble(4) - 0 < 1e-7 || reader.GetString(5).Length == 0)
                    continue;
                Sector cell = new Sector(reader.GetString(0), reader.GetInt32(1), reader.GetInt32(2), reader.GetDouble(3), reader.GetDouble(4), reader.GetString(5));
                cell.FCN = reader.GetInt32(6);
                sectorList.Add(cell);
            }
            reader.Close();

            return sectorList.Count() > 0 ? true : false;
        }
    }

PCIAllocationConfig_KM_0917.xml

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>

    <Database>
        <dbName>PCIOptimize_yf_0122</dbName>
        <server>localhost</server>
        <user>null</user>
        <password>null</password>
    </Database>

<SqlInitSectorInfoTest37900>
    select distinct      tbCell.SECTOR_ID,ENODEBID,PHYCELLID,tbCell.LONGITUDE,tbCell.LATITUDE,tbCell.STYLE ,tbCell.EARFCN
    from tbCell 
    where tbCell.LONGITUDE !=0 and tbCell.LONGITUDE !=0 and
    SECTOR_ID in
   (select sector_id from tbCell37900)
</SqlInitSectorInfoTest37900>

</Configuration>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值