【问题标题】:Singleton pattern and server connection using excel-DNA使用 excel-DNA 的单例模式和服务器连接
【发布时间】:2014-07-11 18:30:33
【问题描述】:

我有一个SQL 数据库。

然后在一个班级我有一个ExcelFunction

[ExcelFunction(Description = "fonction de recherche")]
public static double id(string _isin)
{
   double res;
   res =DBSQL.Instance.getID(_isin);
   return res;
}

然后在另一个类中我有我的连接和单例模式的创建(为了在多线程的情况下是安全的)。这个想法可能不清楚,请问我,我会尽力解释。重点是打开一个连接(使用单例模式),然后发出请求,然后删除单例以关闭连接。

这是我的代码:

public class DBSQL : iAccesDB1
{

    private SqlConnection MaConn = new SqlConnection("sefhgoefhouzeyf");

    private static volatile DBSQL instance;

    private static object syncRoot = new Object();

    private DBSQL() {}

    public static DBSQL Instance
    {   
        get 
        {
           if (instance == null)   
           {
               lock (syncRoot)
               {
                    if (instance == null)
                        instance = new DBSQL();
                }
            }
            return instance;
        }
    }

    public void Connection()    
    {
        MaConn.Open();
    }

    public void CloseConnection()
    {
        MaConn.Close();
    }

    public double getID(String _isin)
    {
        SqlDataReader rd;

        double res = -9999;

        SqlCommand cd = new SqlCommand("select cpn from tD where isin='" + _isin + "'", MaConn);
        try
        {
            rd = cd.ExecuteReader();
            if (rd.HasRows)
            {
                while (rd.Read())
                    res =double.Parse(rd["cpn"].ToString());
            }
        }
        catch (Exception ex)
        {
            throw new Exception("1000: " + ex.Message);
        }
        return res;
    }
}

问题是它不起作用 - 在我的 excel 单元格中,我有以下内容:VALUE?

【问题讨论】:

    标签: c# sql-server excel-dna


    【解决方案1】:

    当您的 Excel-DNA 函数将 #VALUE 返回到 Excel 时,这可能意味着存在未处理的异常。

    我建议您更改您的顶级函数以返回一个“对象”,如果出现异常,该对象会返回一个错误字符串,如下所示:

    [ExcelFunction(Description = "fonction de recherche")]
    public static object id(string _isin)
    { 
        try 
        {
            double res;
            res = DBSQL.Instance.getID(_isin);
            return res; 
        }
        catch (Exception ex)
        {
            return "!!! ERROR: " + ex.ToString();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-28
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 2012-07-30
      相关资源
      最近更新 更多