데이터베이스에 연결하여 작업을 수행하는 Winform을 만들고 싶습니다. 열 때 연결해야하고 사용자가 클릭하여 쿼리를 만듭니다. 나는 최선의 코스가로드 될 때 연결을 열어 모든 다른 클래스에서 액세스 할 수 있도록하는 것이 무엇인지 100 % 확신하지 못합니다. 사용자가 버튼을 클릭 한 다음 쿼리를 만들었지 만 DB 연결 열기를 InitializeComponent() 부분으로 이동 한 다음 구성 요소에서 이동하려고하면 DB 연결을 여는 연결이 작동하도록 테스트를 수행했습니다. 이미 만들어진 연결을 호출하면됩니다.SqlConnection에 대해 Winform에서 전역을 설정하는 최적의 방법
사례별로 사례가 실행되도록 설정했지만 더 나은 방법이 있습니까? 내가 할 수있는 유일한 방법 일 뿐이야? 여기
테스트를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;
}
}
}
흠 시작과 액세스시 각 사용자 동작에 대해 열어 볼 필요가 없으며 각 사용자 동작에서 열리고 닫힙니다. 말 그대로 모든 동작은 쿼리를 작성하므로 아마도 정리할 수있는 더 좋은 방법이 될 수 있습니다. 아마도 내가 열어서 queries.cs 파일에서 만들고 메서드를 닫고 create_concection () 개인 정적? ** 편집 내용을보고 n-tier tk를 보게 될 것입니다 –
이것은 데이터베이스에 지속적으로 연결을 유지하는 문제가 아닙니다. 이 자원은 처분해야합니다. 그렇지 않으면 연결을 열 수없는 상황에서 자신을 찾을 수 있습니다. http://social.msdn.microsoft.com/Forums/is/adodotnetdataproviders/thread/0d5994e1-056e-4fbd-a990-b0198a114afb를 참조하십시오. –
"사용자가 연결을 열 수없는 상황에서 자신을 발견 할 수 있습니다"라는 것은 하나의 사용자 앱이라면 사실입니까? 전에 그걸 읽었습니다.하지만 한 가지 예를 하나만 열면 어떤 문제도 없을 것이라고 생각했습니다. –