2012-11-16 52 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; 
    } 
} 
相关问题