2012-11-16 37 views
3

我熟悉編程中面向對象的主要概念,目前我正在自學如何設計類。創建一個類與SQL數據庫進行交互

我有一個非常簡單的類calld公司。下面是我的代碼至今

using System; 

namespace Addressbook 
{ 
    public class Company 
    { 
     private string _companyId; 
     private string _companyName; 
     private string _companyType; 
     private string[] _companyDetails; 

     public Company() 
     { 

     } 


     public string CompanyId 
     { 
      set 
      { 
       this._companyId = value; 
      } 
     } 

     public string CompanyName 
     { 
      set 
      { 
       this._companyName = value; 
      } 
     } 

     public string CompanyType 
     { 
      set 
      { 
       this._companyType = value; 
      } 
     } 


     public string[] GetCompanyDetails() 
     { 

      return null; 
     } 

    } 
} 

什麼我現在試圖做的是實施一些方法給它,這就是在那裏,我有點失去。

我想到的第一種方法叫做GetCompanyDetails(),它會從SQL數據庫收集數據然後顯示它。可能在DataGridView或其他東西。

我的問題是我無法弄清楚我應該如何寫這個方法。我是否將所有SQL查詢和連接放在裏面?或者我只是將它們的實例作爲參數傳遞?我應該從方法中返回什麼類型?

有人可以給我一些指導方針嗎?

此外,如果您有關於此主題的任何優秀教程/指南的鏈接,請將其發佈。

謝謝。

+0

我無親,但我一直在訓練,宣佈持有的所有查詢返回'string'一個新的類。 –

回答

2

查看「數據源架構模式」部分的模式:http://martinfowler.com/eaaCatalog/index.html。一個ActiveRecord模式可能是你需要去做的事情,儘管你可能最終會走DataMapper/ORM路線。

在雅居樂的精神,我會保持連接和事務管理最初很簡單。也許只是這個類中的一個私有函數。然後,我會讓每個方法在SQL或SP中定義它的查詢並執行它,並對結果進行處理。這將數據訪問邏輯放在適當的位置。

你可能想使你的共享「的getter」功能(S)/靜態,這樣不需要一個實例走了。然後你可以寫這樣的東西:

var companies = Company.GetCompanyDetails(); 

雖然超簡單化,這種方法會讓你去,同時仍然允許範圍擴大。一旦事情變得越來越複雜,這種方法將變得過於簡單。此時,您需要擴展和重構,考慮更強大的連接/事務管理,對象創建和查詢。

2

首先,你的代碼很老舊。您的代碼應該是這樣的

public class Company 
{  
     public string CompanyId { get; set; } 
     public string CompanyName{ get; set; } 
     public string CompanyType{ get; set; }  
} 

當你創建這個類,這意味着創建一個對象Company其中有3場;

Company.CompanyIdCompany.CompanyNameCompany.CompanyType

所以你現在要做的是connecto到SQL服務器,EXCUTE查詢從數據庫中獲取數據,並在對象公司填寫。

例子:

class myConnection 
    { 
     public static SqlConnection GetConnection() 
     { 
      var company = new Company(); 
      string str = "Data Source=localhost/serer Ip;Initial Catalog = YourDatabaseName;uid =sa;pwd = YourPassword"; 

      SqlConnection con = new SqlConnection(str);   
      SqlCommand cmd = new SqlCommand("SELECT * FROM Company WHERE CompanyID = 1", conn); 
      SqlDataReader reader = cmd.ExecuteReader(); 
      while (reader.Read()) 
      { 
       Company.CompanyId = reader["CompanyID"]; 
       Company.CompanyName = reader["Name"]; 
       Company.CompanyType = reader["Type"]; 
      } 
     } 
    } 
4

創建類,它代表在你的表中的記錄

public class Company 
{  
    public string CompanyId { get; set; } 
    public string CompanyName{ get; set; } 
    public string CompanyType{ get; set; }  
} 

獲取與Dapper映射它:

public IEnumerable<Company> GetCompanies() 
{ 
    using (var connection = new SqlConnection(connectionString)) 
    { 
     connection.Open(); 
     return connection.Query<Company>("SELECT * FROM Companies"); 
    } 
} 

如果你不想處理ADO.NET,看看重像Linq 2 Sql,實體框架,NHibernate的重量ORM。

+0

Thx適合短小精悍的小費。不知道。 –

0
String conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; 
OracleConnection con = new OracleConnection(conString); 
string cmdStr = @" SELECT * FROM TABLE WHERE ROW = :param"; 
OracleCommand cmd = new OracleCommand(cmdStr, con); 
OracleDataAdapter da = new OracleDataAdapter(cmd); 
da.SelectCommand = cmd; 
cmd.Parameters.Add("param", "yourValueHere"); 

DataSet ds = new DataSet("dataSet"); 
da.Fill(ds, "dataAdapter"); 
return ds; 

是實現數據庫類的好方法。還記得要標記你的方法

[DataObjectMethod(DataObjectMethodType.Select, true)] 

如果你想它可以在你的WPFs中實現。

0

使用下,我們使用的是作爲類文件:

/// <summary> 
/// Open the Connection when creating the Object 
/// </summary> 
class DataAccess 
{ 
    public SqlConnection sqlConn ; 
    public int gConnTimeOut = 0 ; 

    public DataAccess() 
    { 
     string strConn = "";    

     Classes.GlobVaribles objConStr = Classes.GlobVaribles.GetInstance(); 
     strConn = objConStr.gConString; 
     gConnTimeOut = objConStr.gQueryTimeOut; 

     if (strConn == "") 
     { 
      XmlAccess XmlFile = new XmlAccess(); 
      strConn = XmlFile.Xml_Read("gConStr"); 
      gConnTimeOut = int.Parse(XmlFile.Xml_Read("gQueryTimeOut")); 

      objConStr.gConString = strConn; 
      objConStr.gQueryTimeOut = gConnTimeOut; 
     } 

     sqlConn = new SqlConnection(strConn);    
     sqlConn.Open(); 
    } 

    /// </summary> 
    /// Can use to select one value from SELECT statment 
    /// </summary> 
    public string SQLER(string strSQL) 
    { 
     if (sqlConn.State.ToString() == "Closed") { sqlConn.Open(); } 

     strSQL = SQLFormat(strSQL); 
     SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn); 

     string strResult = sqlCmd.ExecuteScalar().ToString(); 
     sqlCmd.Dispose(); 

     return strResult; 

    } 

    /// </summary> 
    /// Return Data Set   
    /// </summary> 
    public DataSet SQLDT(string strSQL) 
    { 
     //conn.Close(); 

     //if (conn.State.ToString() == "Closed") { conn.Open(); } 
     if (sqlConn.State.ToString() == "Closed") { sqlConn.Open(); } 
     SqlCommand comm = new SqlCommand(); 
     comm.CommandTimeout = gConnTimeOut; 
     SqlDataAdapter adapt = new SqlDataAdapter(); 
     comm.CommandText = strSQL; 
     comm.Connection = sqlConn; 
     adapt.SelectCommand = comm; 

     DataSet dtset = new DataSet(); 
     adapt.Fill(dtset); 
     return dtset; 

    } 

    /// <summary> 
    /// Can use for Execute SQL commands (Insert/Delete/Update) 
    /// </summary> 
    public int SQLCX(string strSQL) 
    { 
     try 
     { 
      if (sqlConn.State.ToString() == "Closed") { sqlConn.Open(); } 

      strSQL = SQLFormat(strSQL); 
      SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn); 
      sqlCmd.CommandTimeout = gConnTimeOut; 
      int intResult = sqlCmd.ExecuteNonQuery(); 
      sqlCmd.Dispose(); 

      return intResult; 
     } 
     catch (Exception objError) 
     { 
      MessageBox.Show("System Error - " + objError.Message.ToString(),"Application Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 
      return -1; 
     } 

    } 

    /// <summary> 
    /// Returns a SQL DataReader 
    /// </summary>  
    public SqlDataReader DataReader(string strSQL) 
    { 
     if (sqlConn.State.ToString() == "Closed") { sqlConn.Open(); } 
     strSQL = SQLFormat(strSQL); 
     SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn); 
     SqlDataReader dataRed = null; 

     dataRed = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection); 
     sqlCmd.Dispose(); 
     return dataRed; 
    } 

    /// <summary> 
    /// Retrun the No of Records 
    /// </summary> 
    public int GetNumOfRec(string strSQL) 
    { 
     /// Use for get No of Records in SELECT command 
     try 
     { 
      int intResult = -1; 
      if (sqlConn.State.ToString() == "Closed") { sqlConn.Open(); } 

      strSQL = SQLFormat(strSQL); 
      SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn); 
      intResult = (int)sqlCmd.ExecuteScalar(); 
      sqlCmd.Dispose(); 

      return intResult; 
     } 
     catch (Exception objError) 
     { 
      MessageBox.Show("System Error - " + objError.Message.ToString(), "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      return -1; 
     } 
    } 

    /// </summary> 
    /// Fill Listview 
    /// </summary> 
    public void ListViewFill(string strSQL, System.Windows.Forms.ListView lstView) 
    { 
     if (sqlConn.State.ToString() != "Open") { sqlConn.Open(); } 
     SqlDataAdapter adapter = new SqlDataAdapter(strSQL, sqlConn);    
     DataSet ds = new DataSet("glorders"); 
     adapter.SelectCommand.CommandTimeout = gConnTimeOut; 
     adapter.Fill(ds, "glorders"); 

     DataTable dt = ds.Tables[0]; 
     int colCount = dt.Columns.Count; 

     lstView.Items.Clear(); 
     Color shaded = Color.FromArgb(240, 240, 240); 
     int j = 0; 

     foreach (DataRow row in dt.Rows) 
     { 
      string[] subitems = new string[colCount]; 

      object[] o = row.ItemArray; 


      for (int i = 0; i < colCount; i++) 
      { 
       subitems[i] = o[i].ToString();      
      } 

      ListViewItem item = new ListViewItem(subitems); 
      lstView.Items.Add(item); 

      if (j++ % 2 == 1) 
      { 
       item.BackColor = shaded; 
       item.UseItemStyleForSubItems = true; 
      } 
     } 

     dt.Dispose(); 
     ds.Dispose(); 
     adapter.Dispose(); 
    } 

    /// </summary> 
    /// Fill ComboBox 
    /// </summary> 
    public void ComboFill(string strSQL, System.Windows.Forms.ComboBox dbCombo) 
    { 
     SqlDataReader dbReader = null; 
     dbReader = DataReader(strSQL); 
     dbCombo.Items.Clear(); 
     while (dbReader.Read()) { dbCombo.Items.Add(dbReader[0].ToString().Trim()); } 
     dbReader.Dispose(); 
    } 

    private string SQLFormat(string strSQL) 
    { 
     strSQL = strSQL.Replace("\r", " "); 
     strSQL = strSQL.Replace("\n", " "); 
     strSQL = strSQL.Replace("\t", " "); 
     strSQL = strSQL.Replace(" ", " "); 
     return strSQL; 
    } 
} 
相關問題