2012-10-17 24 views
0

我想創建一個連接到數據庫來執行操作的winform。它在打開時必須連接,然後根據用戶點擊的內容進行查詢。我不是100%確定加載時打開連接的最佳方法,並且可以從所有不同的類訪問連接。我做了一個測試運行,當用戶點擊按鈕然後進行查詢時,打開數據庫連接的連接工作,但我想將數據庫連接的開放移動到InitializeComponent()部件,然後從組件只需撥打已建立的連接即可。在Winform中爲SqlConnection設置全局優化的方法

我已經設置好了,這樣它就可以在個案上運行,但有沒有更好的方法來做到這一點?我是這樣做的,只有你可以/應該這樣做?

下面是測試

Form1.Designer.cs

namespace end_of_day 
{ 
    using System.Data.SqlClient; 
    partial class Form1 
    { 
     /// <summary> 
     /// Required designer variable. 
     /// </summary> 
     private System.ComponentModel.IContainer components = null; 


     /// <summary> 
     /// Clean up any resources being used. 
     /// </summary> 
     /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> 
     protected override void Dispose(bool disposing) 
     { 
      if (disposing && (components != null)) 
      { 
       components.Dispose(); 
      } 
      base.Dispose(disposing); 
     } 

     #region Windows Form Designer generated code 

     /// <summary> 
     /// Required method for Designer support - do not modify 
     /// the contents of this method with the code editor. 
     /// </summary> 
     private void InitializeComponent() 
     { 
      this.button1 = new System.Windows.Forms.Button(); 
      this.label1 = new System.Windows.Forms.Label(); 
      this.button2 = new System.Windows.Forms.Button(); 
      this.button3 = new System.Windows.Forms.Button(); 
      this.button4 = new System.Windows.Forms.Button(); 
      this.SuspendLayout(); 
      // 
      // button1 
      // 
      this.button1.Location = new System.Drawing.Point(78, 411); 
      this.button1.Name = "button1"; 
      this.button1.Size = new System.Drawing.Size(147, 64); 
      this.button1.TabIndex = 0; 
      this.button1.Text = "Test"; 
      this.button1.UseVisualStyleBackColor = true; 
      this.button1.Click += new System.EventHandler(this.button1_Click); 
      // 
      // label1 
      // 
      this.label1.AutoSize = true; 
      this.label1.Location = new System.Drawing.Point(13, 13); 
      this.label1.Name = "label1"; 
      this.label1.Size = new System.Drawing.Size(199, 13); 
      this.label1.TabIndex = 1; 
      this.label1.Text = "ERROR: didn\'t connect to the database."; 
      // 
      // button4 
      // 
      this.button4.Location = new System.Drawing.Point(78, 201); 
      this.button4.Name = "button4"; 
      this.button4.Size = new System.Drawing.Size(147, 64); 
      this.button4.TabIndex = 4; 
      this.button4.Text = "Print Out of Stock"; 
      this.button4.UseVisualStyleBackColor = true; 
      this.button4.Click += new System.EventHandler(this.button4_Click); 
      // 
      // Form1 
      // 
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 
      this.ClientSize = new System.Drawing.Size(306, 523); 
      this.Controls.Add(this.button4); 
      this.Controls.Add(this.button3); 
      this.Controls.Add(this.button2); 
      this.Controls.Add(this.label1); 
      this.Controls.Add(this.button1); 
      this.Name = "Form1"; 
      this.Text = "End of day"; 
      this.ResumeLayout(false); 
      this.PerformLayout(); 

     } 

     #endregion 

     private System.Windows.Forms.Button button1; 
     private System.Windows.Forms.Label label1; 
     private System.Windows.Forms.Button button4; 
     // NOTE I NEED TO BE ABLE TO CHANGE THE LABEL FROM OTHER CLASSES FIX THIS SOMEHOW 
    } 
} 

Form1.cs的

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.SqlClient; 
using System.Net.Mail; 

namespace end_of_day 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      SqlConnection myConnection = queries.create_concection(); 
      try 
      { 
       SqlDataReader myReader = null; 
       SqlCommand myCommand = new SqlCommand("SELECT TOP 100000 ItemName,Price,In_Stock,Vendor_Part_Num FROM Inventory", 
                 myConnection); 
       myReader = myCommand.ExecuteReader(); 

       String mess = ""; 
       int i = 0; 
       while (myReader.Read()) 
       { 
        if (i < 10) 
        { 

         mess += myReader["ItemName"].ToString(); 
         mess += myReader["Price"].ToString(); 
         mess += "\r\n"; 
        } 
        i++; 
       } 
      } 
      catch (Exception er) 
      { 

       DialogResult dlgRes = MessageBox.Show(er.ToString(), "Error", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); 

      } 

     } 

     private void button4_Click(object sender, EventArgs e) 
     { 
      SqlConnection myConnection = queries.create_concection(); 

      DialogResult dlgRes = MessageBox.Show("Exculde Videos?", 
       "Options", 
       MessageBoxButtons.YesNoCancel, 
       MessageBoxIcon.Question); 

      String SQL_op = ""; 
      if (dlgRes == DialogResult.Yes) 
      { 
       SQL_op = "AND NOT Dept_ID = 'video'"; 
      } 


      try 
      { 

       SqlDataReader myReader = null; 
       SqlCommand myCommand = new SqlCommand("SELECT TOP 100000 ItemName,Price,In_Stock,Vendor_Part_Num FROM Inventory WHERE In_Stock<1 AND NOT Dept_ID = '006' "+ SQL_op+" ORDER BY Dept_ID", 
                 myConnection); 
       myReader = myCommand.ExecuteReader(); 

       String mess = ""; 
       int i = 0; 
       while (myReader.Read()) 
       { 
        if (i < 10) 
        { 

         mess += myReader["ItemName"].ToString(); 
         mess += myReader["Price"].ToString(); 
         mess += "\r\n"; 
        } 
        i++; 
       } 


       dlgRes = MessageBox.Show("Had " + i + "items including: \r\n" + mess, 
       "Confirm Document Close", 
       MessageBoxButtons.YesNoCancel, 
       MessageBoxIcon.Question); 

      } 
      catch (Exception er) 
      { 

       dlgRes = MessageBox.Show(er.ToString(), "Error", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); 


      } 
     } 
    } 
} 

queries.cs

using System; 
using System.Collections.Generic; 
using System.Xml; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.SqlClient; 
using System.Web; 


namespace end_of_day 
{ 
    public class queries 
    { 
     public static SqlConnection create_concection() 
     { 
      Boolean hasConection =true; 
      SqlConnection myConnection = new SqlConnection(
       "Data Source=localhost\\SQLEXPRESS;" + 
       "Trusted_Connection=true;" + 

       "Initial Catalog=TESTDB; " + 
       "connection timeout=30" 
      ); 
      try 
      { 
       myConnection.Open(); 
      } 

       catch (Exception er) 
       { 
        hasConection = false; 
        DialogResult dlgRes = MessageBox.Show(er.ToString(), "Error", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); 
       } 


      if (hasConection) { 
       // THIS SHOULD CHANGE THE LABEL OF THE MAIN FORM 
       //Form1 form = new Form1(); 
       //form.MyMessage = "made it"; 
      } 
      return myConnection; 
     } 
    } 
} 

回答

0

這是印度政府ng打開時必須連接,然後根據用戶點擊的內容進行查詢。 ... 我已經設置好了,這樣它就可以在一個個案的情況下運行,但有沒有 更好的方法來做到這一點?

還有絕對是更好的方法。是否不是當表單加載時打開一個連接,並將其保持打開狀態。

您應該始終遵循的經驗法則是僅在需要時纔打開連接,並在完成使用後立即關閉連接。這意味着在實踐中,只有在需要運行查詢(儘可能接近實際查詢執行)時纔打開它,然後在查詢完成後立即關閉連接。

我不是100%肯定,最好的辦法就是打開連接時 IT負載,使這一方面能夠從所有 不同類訪問

你問什麼關於如何設計你的應用程序,你會得到一個常見的答案是使用n層設計。你應該閱讀multitier architectures

+0

嗯,在開始時打開它並獲取每個用戶操作的開啓和關閉每個用戶操作的開啓和關閉沒有任何收益?從字面上看,每個動作都會進行查詢,所以想到也許會有更好的方法來組織事物。可能我應該打開並關閉它們,這些方法將在queries.cs文件中製作,並使create_concection( )私有靜態? **我看到你的編輯,並會看到n層tk –

+0

這不是一個收益問題,它是一個與數據庫保持連接的問題,打開。這是您需要處理的資源,否則,您可能發現自己處於無法打開連接的情況。請參閱http://social.msdn.microsoft.com/Forums/is/adodotnetdataproviders/thread/0d5994e1-056e-4fbd-a990-b0198a114afb。 –

+0

在「您可能發現自己處於無法打開連接的情況下」,如果是單用戶應用程序,那麼這是否屬實?我之前已經閱讀過那篇文章,但是我想如果我只打開一個連接並且只有一個連接沒有問題? –