2014-06-20 25 views
0

我已經能夠通過Internet上的精彩指南幫助MySQL與我的C#WinForms應用程序接口,但我很困惑,哪種「方法」是這樣做的標準方式,如果有的話它確實存在。詳細說明一下,我將首先描述我正在開發的應用程序。使用C#&MySQL

C#應用概述

我的應用程序接受來自用戶的輸入,使用DataGridView作爲CRUD主控制,並生成Excel報表。基本上,它的下面:

  • 接受輸入和插入所述數據到數據庫
  • 檢索記錄,並使用CellValueChanged事件通過DataGridView
  • 更新記錄顯示他們
  • 刪除記錄
  • 生成使用Crystal Reports的報告

使用Obj ects

我目前所做的是將數據存儲和檢索爲對象,並將其用於所有上述操作。例如:

public class Cat 
{ 
    private int id; 
    public int Id 
    { 
     get { return id; } 
     set { id = value; } 
    } 

    private string breed; 
    public string Breed 
    { 
     get { return breed; } 
     set { breed = value; } 
    } 

    public Cat(int id, string breed) 
    { 
     this.id = id; 
     this.breed = breed; 
    } 
} 

對我來說,檢索數據,我做的:

public void FillCats() 
    { 
     cats = new List<Cat>(); 

     conn.Open(); 

     string query = "SELECT * from cat;"; 

     MySqlCommand cmd = new MySqlCommand(query, conn); 
     MySqlDataReader reader = cmd.ExecuteReader(); 

     while (reader.Read()) 
     { 
      Cat cat = new Cat(
       Convert.ToInt32(reader[0]), 
       reader[1].ToString(), 
      ); 
      cats.Add(cat); 
     } 

     reader.Close(); 
     conn.Close(); 
    } 

同樣,我的創建,更新和刪除操作是簡單的下面創建功能的變種:

public void Insert(DatabaseDriver db) 
    { 
     string insert = @" 
     INSERT INTO cat(id, breed) 
     VALUES(?id, ?breed);"; 

     db.open(); 
     db.setQuery(insert); 
     db.setParameter("id", this.id); 
     db.setParameter("breed", this.breed); 
     db.executeNonQuery(); 
     db.close(); 
    } 

我正在做對嗎?

當然,它確實有效,但我想知道是否有一種更省時的方法,可能類似於創建DBML文件會自動將應用程序連接到SQL Server數據庫,甚至自動關聯每個屬性及其相應的主鍵。在任何人問起之前,不幸的是,我不能使用SQL Server。

+0

您應該考慮使用數據集和實體框架,使您的工作變得更加簡單。然後,您可以將DataGridView綁定到從數據庫模式形成的數據集。 –

回答

0

退房這個答案做這件事的方式要少得多,涉及:Fill Datagridview with MySQL data

作爲一個側面說明,你可以簡單地調用reader.GetInt32(0)reader.GetString(1)代替Convert.ToInt32(reader[0])reader[1].ToString()。這樣,當品種爲空時,您不會得到NullReferenceException。