Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Winforms 在Winform中为SqlConnection设置全局连接的最佳方法_Winforms_C# 4.0_Sqlconnection - Fatal编程技术网

Winforms 在Winform中为SqlConnection设置全局连接的最佳方法

Winforms 在Winform中为SqlConnection设置全局连接的最佳方法,winforms,c#-4.0,sqlconnection,Winforms,C# 4.0,Sqlconnection,我想创建一个winform,它连接到一个数据库来做一些事情。它必须在打开时进行连接,然后根据用户单击的内容进行查询。我不能100%确定最好的方法是在加载时打开连接,并使该连接能够从所有不同的类访问。我已经进行了一次测试运行,以使连接正常工作,当用户单击按钮并进行查询时,该连接将打开DB连接,但我希望将DB连接的打开移动到InitializeComponent()部分,然后从组件调用已建立的连接 我已经设置好了,这样就可以逐案运行,但是有更好的方法吗?我这样做是你唯一能/应该做的吗 这是测试 Fo

我想创建一个winform,它连接到一个数据库来做一些事情。它必须在打开时进行连接,然后根据用户单击的内容进行查询。我不能100%确定最好的方法是在加载时打开连接,并使该连接能够从所有不同的类访问。我已经进行了一次测试运行,以使连接正常工作,当用户单击按钮并进行查询时,该连接将打开DB连接,但我希望将DB连接的打开移动到InitializeComponent()部分,然后从组件调用已建立的连接

我已经设置好了,这样就可以逐案运行,但是有更好的方法吗?我这样做是你唯一能/应该做的吗

这是测试

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
    }
}
它必须在打开时连接,然后根据 用户单击,进行查询。 ... 我已经设置好了,这样就可以逐案运行,但是否有 这样做更好吗

绝对有更好的方法。请勿在窗体加载时打开连接,并保持打开状态

您应该始终遵循的一条经验法则是,仅在需要时打开连接,并在使用完毕后立即关闭连接。这意味着在实践中,只有在需要运行一个查询(尽可能接近实际的查询执行)并在查询完成后立即关闭连接时,才能打开它

我不是100%确定什么时候最好打开连接 它加载并使该连接能够从所有服务器访问 不同类别


您要问的是如何设计您的应用程序,而您将得到的一个常见答案是使用n层设计。您应该继续阅读。

hmm在开始和访问每个用户操作时打开它,与在每个用户操作时打开和关闭相比,没有任何好处?从字面上说,每一个动作都会产生一个疑问,所以我的想法是也许会有更好的方式来组织事情。。也许我应该在querys.cs文件中创建的方法中打开和关闭它们,并将其创建为私有静态?**我看到了您的编辑,并将查看n-tier tkIt。这不是增益的问题,而是保持与数据库的持久连接的问题,打开。这是您需要处理的资源,否则,您可能会发现自己处于无法打开连接的情况。请参阅。在“您会发现自己处于无法打开连接的情况”中,如果是单用户应用程序,这是真的吗?我以前读过这篇文章,但我想如果我只打开一个实例的一个连接,就不会有问题了?
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);


            }
        }
    }
}
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;
        }
    }
}