2012-03-16 87 views
0

使用DLL访问数据库是否明智当应用程序启动时。创建DLL以访问数据库c#

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

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(字符串,System.Data.SqlClient.SqlConnection)”具有一些无效参数
是误差我得到

我会做什么没有堆栈溢出。

+0

如果你问为什么这条线路失败,你可以发布更多的代码?是否调用过Initialize()? – Jason 2012-03-16 09:26:23

+1

“它不会工作”不是很有帮助。发生了什么,你期望会发生什么?你有错误信息吗? – Heinzi 2012-03-16 09:28:26

+0

@Jason Typo现在更新 – deception1 2012-03-16 09:31:07

回答

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); 

编辑:另外在初始化,您已经创建SqlConnection对象,但不叫Open()。在尝试使用连接之前,您需要执行此操作。在调用SqlCommand之前,可以将connection.Open()添加到initialise()或调用myConnection.connection.Open()

2

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