WinForm/C# C# 操作 Oracle 数据库及工具类简单封装

xinggang · 2019年08月07日 · 157 次阅读

连接字符串

<add name="connOA_GK" connectionString="User Id=xxx;Password=xxx;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.200.0.53)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=ecology)))" />

DLL 引用

Oracle.ManagedDataAccess.dll

操作工具类

using System;
using System.Data;
using Oracle.ManagedDataAccess.Client;

namespace PEMSoft.Web.AppServer.Common
{
    public class OracleHelper
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private string connStr = "";

        /// <summary>
        /// 最新一次执行出错的错误信息
        /// </summary>
        public string ErrMsg;

        public OracleHelper(string connStr)
        {
            this.connStr = connStr;
        }

        /// <summary>
        /// 执行SQL语句,返回受影响行数
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public int ExecSql(string sql, params OracleParameter[] parameters)
        {
            try
            {
                using (OracleConnection conn = new OracleConnection(connStr))
                {
                    conn.Open();
                    using (OracleCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = sql;
                        cmd.Parameters.AddRange(parameters);
                        return cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
                return -1;
            }
        }

        /// <summary>
        /// 执行SQL语句,返回DataTable
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public DataTable GetDataTable(string sql, params OracleParameter[] parameters)
        {
            try
            {
                using (OracleConnection conn = new OracleConnection(connStr))
                {
                    conn.Open();
                    using (OracleCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = sql;
                        cmd.Parameters.AddRange(parameters);
                        OracleDataAdapter adapter = new OracleDataAdapter(cmd);
                        DataTable datatable = new DataTable();
                        adapter.Fill(datatable);
                        return datatable;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
                return null;
            }
        }
    }
}
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册