【问题标题】:Create DLL to access database c#创建DLL以访问数据库c#
【发布时间】:2012-03-16 09:22:21
【问题描述】:

在应用程序启动时使用 Dll 访问数据库是否明智?

这是我必须在我的应用程序的每个页面中调用的代码

  SqlConnection myConnection = new SqlConnection();
    myConnection.ConnectionString = "Data Source=CRYSTAL5\\INSTANCE1;Initial Catalog=Pharmacy;Integrated Security=True";
    myConnection.Open(); 

还有我写的dll代码

public  class DBConnect
    {
        public DBConnect()
        {
            Initialize();
        }
        private SqlConnection connection;
        //Constructor


    //Initialize values
    private void Initialize()
    {
        string connectionString;
        connectionString = "Data Source=CRYSTAL5\\INSTANCE1;Initial Catalog=Pharmacy;Integrated Security=True";

        connection = new SqlConnection(connectionString);
    }

然后我在我的应用中添加了using DBCon; 并尝试运行此代码

DBConnect myConnection = new DBConnect();
        SqlCommand myCommand = new SqlCommand("select doc_fname,doc_lname,gender,department,education ,NMC_no  from ph.doctor_info where unit_id =0", myConnection);

它不会起作用。

抱歉描述太差了

“System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)”的最佳重载方法匹配有一些无效参数
是我得到的错误

如果没有堆栈溢出,我该怎么办。

【问题讨论】:

  • 如果你问为什么那行失败,你能发布更多代码吗? Initialize() 有人打电话吗?
  • “它不起作用”不是很有帮助。会发生什么,您期望会发生什么?您收到错误消息吗?
  • 您尝试使用自己的 DBConnect 对象而不是 SqlConnection 实例来创建 SqlCommand。那是行不通的。您可以向 DBConnect 添加一个 CreateSqlCommand-Method,以便 DBConnect 在将命令传回给您之前创建命令对象并注入 SqlConnection 实例。

标签: c# wpf visual-studio-2010 dll


【解决方案1】:

您将“DbConnect”类型的对象传递给 SqlCommand 而不是 SqlConnection 对象。您的 sql 连接对象保存在此类中,在 connection 变量中。

您需要将此字段设为公开,或者创建一个返回数据连接的函数。

如果公开连接,你会这样做:

SqlCommand myCommand = new SqlCommand("select doc_fname,doc_lname,gender,department,education ,NMC_no  from ph.doctor_info where unit_id =0", myConnection.connection);

编辑:同样在 Initialise 中,您创建了 SqlConnection 对象,但未调用 Open()。在尝试使用连接之前,您需要执行此操作。将connection.Open() 添加到initialise(),或者在调用SqlCommand 之前调用myConnection.connection.Open()

【讨论】:

    【解决方案2】:

    DBConnect 似乎没有公开 SqlConnection 对象。因此,您将 DBConnect 对象传递给 SqlCommand 构造函数而不是 SqlConnection 对象,因此会出现错误。

    【讨论】:

      猜你喜欢
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 2013-10-15
      • 1970-01-01
      • 2015-10-08
      • 2012-08-21
      • 1970-01-01
      相关资源
      最近更新 更多