Declaring SqlConnection throughout one form

后端 未结 4 1624
感情败类
感情败类 2020-12-22 02:25

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

I am looking to design a small program that will Add/Edit/Dele

相关标签:
4条回答
  • 2020-12-22 02:33

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

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

    Example:

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-22 02:54

    Add your connection string in web.config file

    <connectionStrings>
      <add name="CustomerDataConnectionString" connectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind"
        providerName="System.Data.SqlClient" />
    </connectionStrings>
    

    and in aspx form

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection string"].ToString());
    

    for more information use this link

    0 讨论(0)
  • 2020-12-22 02:55

    Of course, you dont need to have multiple SqlConnection instances. for most application, one connection is sufficient. sqlCommand on the other hand is another thing: You might step into trouble if reusing it, but this is more a design issue than a technical thing.

    I would suggest you move all your database access code to another class ("DataProvider"/"DatabaseController" or whatever name you think is sufficient) to properly encapsulate the code parts. There is no need for a form to directly handle SqlConnection or sqlCommand objects, let it indirectly happen via public methods of that controller type:

    public class DataController
    {
        private SQLConnection Connection {get; set;
        public void DataTable LoadDataFromDatabase()
        {
            ...
        }
        ...
     }
    
    0 讨论(0)
  • 2020-12-22 02:57

    Its better to use single connection string,declare your connection in web.config file and call it in aspx.cs

    0 讨论(0)
提交回复
热议问题