通过一种形式声明 SqlConnection [英] Declaring SqlConnection throughout one form

查看:25
本文介绍了通过一种形式声明 SqlConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关 C# 的一些建议 - 请记住,我只是 C# 的初学者 &Sql.

I'm looking for some advise on C# - Please bare in mind that i'm only a beginner with C# & Sql.

我希望设计一个小程序,可以添加/编辑/删除并运行所有链接到 Sql 数据库的报告.

I am looking to design a small program that will Add/Edit/Delete and run reports all linked to Sql database.

我希望在同一表单的不同区域中包含多个函数和 Sql 查询.

I wish to include multiple functions and Sql queries within different areas on the same form.

示例:1. 我希望有一个可以进行搜索的组合框(Select * from dbo.table)2. 我有一个按钮,单击该按钮时会显示另一个 dbo.table 中的所有信息.

Example: 1. I wish to have a combo box that does a search (Select * from dbo.table) 2. I have a button that when clicked displays all information from another dbo.table.

我的问题是:

我是否必须多次声明我的 Sqlconnection 或者可以在我的:

Would I have to declare my Sqlconnection multiple times or can this be declared within my:

public partial class MainMenu : Form
{
    SqlConnection mmConnection = new SqlConnection("#");
    SqlCommand mmCommand = new SqlCommand();
    SqlDataReader reader;
}

然后我可以使用:

mmConnection.Open();
mmConnection.Close();

任何建议都会很棒.如果我可以在表单顶部声明,它将使我的代码更清晰.

Any advise would be fantastic. If I can declare at the top of my form it would keep my code cleaner.

最诚挚的问候,扎克·哈格里夫斯.

Kindest Regards, Zak Hargreaves.

推荐答案

考虑将您的 SqlConnection 声明为主表单的字段(如果您不想在任何其他表单上使用它).

Consider to declare your SqlConnection as field of your main form (if you don't want to use it on any other form).

注意:添加对 System.Configuration 程序集的引用以使用 ConfigurationManager 类.

Note: Add reference to System.Configuration assembly in order to use ConfigurationManager class.

示例:

public partial class MainMenu : Form
{
    SqlConnection _myConnection;

    public Form1()
    {
        InitializeComponent();

        this._myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
    }

    public void ExecuteAQueryExample()
    {
        if (this._myConnection.State != ConnectionState.Open) this._myConnection.Open();

        using (var command = this._myConnection.CreateCommand())
        {
            // ...
        }

        this._myConnection.Close();
    }
}

这篇关于通过一种形式声明 SqlConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆