如何编写一个应该从数据库中获取数据以在C#中的表单上显示的方法 [英] How do I write a method which is supposed to get data from data base to show on a form in C#

查看:69
本文介绍了如何编写一个应该从数据库中获取数据以在C#中的表单上显示的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Im a beginner to .net and could you guide me to right direction. My problem is based on the following code. Here I have 4 variations of same method and all 4 variations are working fine. But I just want to know what is the best or standard way of doing this?

Code explanation.
From a windows form Im calling 'viewAccount()' method which is in 'bankAccount' class. Its purpose is to get relivant bank account details of a employee from the data base and then those details should be shown in the text boxes of calling form.

Also please note that I have reduced no of line to make it more readable. Appreciate your any help towards the right direction.

Thank you.

Example 01 - Method will return a 'bankAccount' abject with fields populated with data from the data base 










 class bankAccount
{
    //Member fields...
    string acNo;
    string acName;
    string bank;
    string acType;
    frmShowAccount form=new frmShowAccount();


    public bankAccount viewAccount( string acNo )
    {
        this.acNo = acNo;

        using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
        {
            SqlCommand newCmd = new SqlCommand("SELECT Employee.Name, BankAccount.ac_name, BankAccount.bank_name, BankAccount.ac_type FROM BankAccount INNER JOIN Employee ON BankAccount.emp_id = Employee.Emp_ID WHERE (BankAccount.ac_no = @bankAccount)", newCon);

            newCmd.Parameters.Add("@bankAccount", SqlDbType.Char).Value = acNo;
            newCon.Open();
            SqlDataReader rdr = newCmd.ExecuteReader();
            rdr.Read();

            form.txtEmpName.text = rdr.GetString(0); //EmpName is not a member of bankAccount class
            this.acName = rdr.GetString(1);
            this.bank = rdr.GetString(2);
            this.acType = rdr.GetString(3);

            return this;
        }
    }
}





********

//调用上面的方法......



********
//CALLING THE ABOVE METHOD...

bankAccount newBA=new bankAccount();
newBA=newBA.viewAccount(txtACNo.text);//A reference is set to the instance returned
txtACName.text=newBA.acName; //Get the value of instance field to text box





示例02 - Method将返回一个数据读取器,表单将使用它来获取数据





Example 02 - Method will return a data reader and it will be used by the form to get data

class bankAccount
{

    string acNo;
    string acName;
    string bank;
    string acType;

    public SqlDataReader viewAccount( string acNo )
    {
        this.acNo = acNo;

        using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
        {
            SqlCommand newCmd = new SqlCommand("Same SELECT …",newCon);

            newCmd.Parameters.Add()…
            newCon.Open();
            SqlDataReader rdr = newCmd.ExecuteReader();
            rdr.Read();

            return rdr;
        }
    }
}





******** *****

//调用上述方法......





*************
//CALLING THE ABOVE METHOD...

bankAccount newBA=new bankAccount();
SqlDataReader rdr=newBA.viewAccount(txtACNo.text) //A reference to hold the returning reader from the method call
txtACName.text=rdr.getString(1); //Get the value through the reader to text box







示例03 - 此方法需要返回值,但显式为文本框中的值分配






Example 03 - This method want return values but explicitly assign values to the text boxes in the form

class bankAccount
  {

      string acNo;
      string acName;
      string bank;
      string acType;
      frmShowAccount form=new frmShowAccount();

      public void viewAccount( string acNo )
      {
          this.acNo = acNo;

          using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
          {
              SqlCommand newCmd = new SqlCommand("Same SELECT …", newCon);

              newCmd.Parameters.Add()…
              newCon.Open();
              SqlDataReader rdr = newCmd.ExecuteReader();
              rdr.Read();

              // Setting values to the text boxes in the current instance of form
              form.txtName.text=rdr[0];
              form.txtACName.text=rdr[1];
              form.txtBankName.text=rdr[2];
              form.txtACType.text=rdr[3];
          }
      }
  }





******** ****

//调用上面的方法





************
//CALLING THE ABOVE METHOD

bankAccount newBA=new bankAccount();
newBA.form.this; // reference 'form' which is in the 'bankAccount' class is set to current instance of the form object.







例04 - 此方法希望返回任何值。它只会用数据初始化类的实例字段






Example 04 - This method want return any value. It will only initialize instance fields of the class with the data

class bankAccount
{

    string acNo;
    string acName;
    string bank;
    string acType;
    frmShowAccount form=new frmShowAccount();

    public void viewAccount( string acNo )
    {
        this.acNo = acNo;

        using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
        {
            SqlCommand newCmd = new SqlCommand("Same SELECT …)", newCon);

            newCmd.Parameters.Add()…
            newCon.Open();
            SqlDataReader rdr = newCmd.ExecuteReader();
            rdr.Read();

            form.txtName.text=rdr[0];
            this.acName=rdr[1];
            this.bank=rdr[2];
            this.acType=rdr[3];
    }
}





************* **

调用上面的方法





***************
CALLING THE ABOVE METHOD

bankAccount newBA=new bankAccount();
txtACName.text=newBA.acName; // Text boxes get the data from account object's instance fields (probably through a get property)

推荐答案

我已经纠正了将db代码与实体分开的解决方案。



我建议让数据库逻辑远离代码的其余部分:



I've corrected my solution for separating db code from entity.

I suggest to keep database logic away from the rest of the code:

public class BankAccount
{
    public string acNo { get; set; }
    public string acName { get; set; }
    public string bank { get; set; }
    public string acType { get; set; }
}

public class BankaccountFactory 
{
    private BankaccountFactory() { } // Default constructor private, so use factory method

    public static BankAccount CreateFromDb(string acNo)
    {
        BankAccount account = new BankAccount { acNo = acNo };

        using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
        {
            SqlCommand newCmd = new SqlCommand("Same SELECT …)", newCon);

            newCmd.Parameters.Add();
            newCon.Open();
            SqlDataReader rdr = newCmd.ExecuteReader();
            rdr.Read();

            account.acName = rdr[1];
            account.bank = rdr[2];
            account.acType = rdr[3];
        }
        return account;
    }
}





然后在表格中使用它:





Then use it like this in your form:

BankAccount acc = BankAccountFactory.CreateFromDB("1021577552254");

txtACName.text=account.acName;
txtBankName.text=account.bank;
txtACType.text=acType;	





根据您的问题:是的,最好对您项目中的所有实体执行此操作。如果您在更多项目中使用实体,建议将它们放在单独的类库中以重复使用它们。



According to your question: Yes, it is good practise to do this for all entities in your project. If you are using your entities in more projects it is good advice to place them in a separate class library to reuse them.


对于您的特定情况,第一种方法是可以的,因为它分离了来自表示逻辑的数据访问逻辑。



其他方法都是不好的做法。请记住,引入图层(数据访问,业务和演示)背后的核心原则是每个层都用于执行特定任务。例如,数据访问层仅用于执行数据访问活动,仅此而已。业务层负责编码业务逻辑,而不关心数据获取背后的机制,类似表示层仅用于查看业务层处理的数据。因此,您可以看到明确的责任分离。
For your specific case the first method is okay as it is separating the data access logic from presentation logic.

Rest of the approaches are bad practices. Do remember that the core principle behind introducing layers (Data Access, Business and Presentation) is that each layer is meant to do specific task. For example data access layer is meant to do only data access activities, nothing more. Business Layer is responsible for coding business logic and do not care about the mechanism behind data fetching, similarly Presentation layer is only meant to view the data processed by business layer. So there is clear separation of responsibilities as you can see.


这篇关于如何编写一个应该从数据库中获取数据以在C#中的表单上显示的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆