1. 程式人生 > >C# 簡單操作神通OSCAR資料庫

C# 簡單操作神通OSCAR資料庫

說明:

(1)需要引用 System.Data.OscarClient.dll ,此外此應用程式執行目錄需要4個檔案(如下圖),檔案可以在神通庫安裝目錄下查詢;

(2)程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OscarClient;

namespace DC.DBHelp.ShenTong
{
    /// <summary>
    /// 神舟通用OSCAR資料庫
    /// </summary>
    public class ShenTongHelper
    {
        private string _strConn;

        public ShenTongHelper(Common.DbInfo di)
        {
            _strConn = GetConnStr(di);
        }

        /// <summary>
        /// 獲取連線字串
        /// </summary>
        /// <param name="di"></param>
        /// <returns></returns>
        private string GetConnStr(Common.DbInfo di)
        {
            OscarConnectionStringBuilder sbConn = new OscarConnectionStringBuilder
            {
                //IP地址
                Host = string.IsNullOrEmpty(di.DbAdd) ? "127.0.0.1" : di.DbAdd,
                //埠號
                Port = string.IsNullOrWhiteSpace(di.DbPort) ? 2003 : Convert.ToInt32(di.DbPort),
                //資料庫名稱
                Database = string.IsNullOrWhiteSpace(di.DbName) ? "OSRDB" : di.DbAdd,
                //使用者名稱
                UserName = string.IsNullOrWhiteSpace(di.DbUser) ? "SYSDBA" : di.DbUser,
                //密碼
                Password = string.IsNullOrWhiteSpace(di.DbUserPwd) ? "szoscar55" : di.DbUserPwd
            };
            return sbConn.ToString();
        }

        /// <summary>
        /// 資料庫連線測試
        /// </summary>
        /// <param name="di"></param>
        /// <param name="errInfo">連線失敗時的異常資訊</param>
        /// <returns></returns>
        public bool ConnectTest(Common.DbInfo di, out string errInfo)
        {
            errInfo = string.Empty;
            try
            {
                string str = GetConnStr(di);
                OscarConnection conn = new OscarConnection(str);
                conn.Open();
                conn.Close();
            }
            catch (Exception ex)
            {
                errInfo = $"連線失敗。失敗原因如下:{ex.Message}";
            }
            return string.IsNullOrEmpty(errInfo);
        }

        /// <summary>
        /// 執行SQL,獲取資料集DataSet
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="timeout">超時設定</param>
        /// <returns></returns>
        public DataSet ExecuteSqlGetDs(string sql, int timeout = 0)
        {
            using (OscarConnection conn = new OscarConnection(_strConn))
            {
                conn.Open();
                using (OscarCommand cmd = new OscarCommand(sql, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    if (timeout > 0) cmd.CommandTimeout = timeout;

                    OscarDataAdapter ada = new OscarDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    ada.Fill(ds);
                    return ds;
                }
            }
        }

        /// <summary>
        ///  執行SQL,獲取資料集DataTable(前N行)
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="topRows">返回行數</param>
        /// <param name="timeout">超時設定</param>
        /// <returns>資料集DataTable</returns>
        public DataTable ExecuteSqlGetDt(string sql, int topRows = 0, int timeout = 0)
        {
            using (OscarConnection conn = new OscarConnection(_strConn))
            {
                conn.Open();
                using (OscarCommand cmd = new OscarCommand(sql, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    if (timeout > 0) cmd.CommandTimeout = timeout;

                    OscarDataAdapter ada = new OscarDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    ada.Fill(0, topRows, dt);
                    return dt;
                }
            }
        }

        /// <summary>
        /// 執行SQL,返回受影響行數(插入、更新、刪除)
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="timeout">超時設定</param>
        /// <returns>異常資訊,為空時說明執行成功;非空執行失敗</returns>
        public int ExecuteSqlNonQuery(string sql, int timeout = 0)
        {
            using (OscarConnection conn = new OscarConnection(_strConn))
            {
                conn.Open();
                using (OscarCommand cmd = new OscarCommand(sql, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    if (timeout > 0) cmd.CommandTimeout = timeout;

                    return cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        ///  執行SQL(事務),返回異常資訊(插入、更新、刪除)
        /// </summary>
        /// <param name="timeOut"></param>
        /// <param name="sqls"></param>
        /// <returns></returns>
        public string ExecuteSqlNonQueryTran(int timeOut = 0, params string[] sqls)
        {
            string strResult = "";
            OscarConnection conn = new OscarConnection(_strConn);
            conn.Open();
            OscarTransaction sqlTran = conn.BeginTransaction();
            try
            {
                OscarCommand cmd = conn.CreateCommand();
                cmd.Transaction = sqlTran;
                cmd.CommandType = CommandType.Text;
                if (timeOut > 0) cmd.CommandTimeout = timeOut;

                foreach (string sql in sqls)
                {
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                }
                sqlTran.Commit();
            }
            catch (Exception ex)
            {
                strResult = ex.Message;
                sqlTran.Rollback();
            }
            finally
            {
                conn.Close();
                sqlTran.Dispose();
                conn.Dispose();
            }
            return strResult;
        }

        /// <summary>
        /// 獲取資料庫名稱、編碼方式
        /// </summary>
        /// <returns></returns>
        public DataTable GetDbNameList()
        {
            using (OscarConnection conn = new OscarConnection(_strConn))
            {
                conn.Open();
                DataTable dta = conn.GetSchema("Databases");
                if (dta == null) return null;
                DataTable dt = new DataTable();
                dt.Columns.Add("Name");
                foreach (DataRow dra in dta.Rows)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = dra["DATABASE_NAME"].ToString().Trim();
                    dt.Rows.Add(dr);
                }
                return dt;
            }
        }

        /// <summary>
        /// 獲取所有表名
        /// </summary>
        /// <returns></returns>
        public DataTable GetTableNameList()
        {
            using (OscarConnection conn = new OscarConnection(_strConn))
            {
                conn.Open();
                DataTable dta = conn.GetSchema("Tables");
                if (dta == null) return null;
                DataTable dt = new DataTable();
                dt.Columns.Add("Name");
                foreach (DataRow dra in dta.Rows)
                {
                    if (dra["TABLE_SCHEMA"].ToString().Trim() == "STAGENT") continue;
                    DataRow dr = dt.NewRow();
                    dr[0] = dra["TABLE_NAME"].ToString().Trim();
                    dt.Rows.Add(dr);
                }
                return dt;
            }
        }

        /// <summary>
        /// 獲取列資訊
        /// TABLE_NAME,COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,ORDINAL_POSITION
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public DataTable GetColumnInfo(string tableName)
        {
            using (OscarConnection conn = new OscarConnection(_strConn))
            {
                conn.Open();
                DataTable dta = string.IsNullOrWhiteSpace(tableName)
                    ? conn.GetSchema("Columns", new string[] {null, null, null})
                    : conn.GetSchema("Columns", new string[] {null, null, tableName.ToUpper()});
                return dta;
            }
        }

        
    }
}

(3)神舟庫安裝後,開啟“SQL互動工具”,點選“幫助”,裡面簡介應該可以解決一般問題了。