【问题标题】:C# Can I Make an sqlConnection public and refer to it from other forms?C# 我可以公开一个 sqlConnection 并从其他表单中引用它吗?
【发布时间】:2011-07-22 04:28:32
【问题描述】:

我的第一个表单上有一个 sqlConnection,我想知道是否可以将其公开,以便我可以从其他表单中引用它。到目前为止我的代码如下,但我不知道我会在哪里公开或如何公开。

public partial class frmConnect : Form
{

    public frmConnect()
    {
        InitializeComponent();
    }

    private void btnConnect_Click(object sender, EventArgs e)
    {
        String server;

        server = cmbConnect.SelectedItem.ToString();

        MessageBox.Show(server);

        sqlConnectionNW.ConnectionString = "Data Source=" + server + ";Initial Catalog=Northwind;Integrated Security=True";

        try
        {
            sqlConnectionNW.Open();

            MessageBox.Show("Successfully Connected!");

            frmSignIn frmLogIn = new frmSignIn();

            frmLogIn.server = server;

            sqlConnectionNW.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

        }

    }
}

}

【问题讨论】:

    标签: c# public sqlconnection


    【解决方案1】:

    我建议你不要这样做。为了访问数据库,最好使用它自己的类,在那里您将拥有与数据库交互的所有方法(选择、插入、更新和删除查询)。而且每一个方法都有自己的 SqlConnection 实例化(新对象的创建)。

    你可以这样做:

    public class WorkWithDataBase
    {
        private void SomeMethod()
        {
            using(SqlConnection sqlConn = new SqlConnection("connectionString"))
            {
                //rest of the code
                sqlConn.Open(); //if needed)
                //and no need to close the connection, becuase "using" will take care of that!
            }
        }
    }
    

    希望对你有帮助, 米贾

    【讨论】:

      【解决方案2】:

      我假设您的连接对象保存在类的字段或属性中。这样做通常不是一个好主意,即使该字段或属性是私有的。

      最佳做法是将连接作为局部变量保留在需要的地方。尽可能晚地打开它们并尽可能早地关闭它们,最好将它们包装在 using 块中。

      【讨论】:

        【解决方案3】:

        您应该将表单中的连接和所有处理提取到它自己的类中——您可以将其称为DataHandling。将其传递到表单以及您想使用的任何地方。

        :-)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-04
          • 2011-04-26
          • 2011-06-11
          • 1970-01-01
          • 2020-08-09
          • 1970-01-01
          • 1970-01-01
          • 2015-02-02
          相关资源
          最近更新 更多