2015-01-05 35 views
-1

我的app.config文件:如何從應用程序配置獲取連接字符串在C#

<configuration> 
    <connectionStrings> 
     <add name="MegaPixelBizConn" 
      connectionString="Data Source=PSHERATH-PC;Initial Catalog=MegaPixelBiz;Integrated Security=True" 
      providerName="System.Data.SqlClient" /> 
    </connectionStrings> 
</configuration> 

然後創建DBConnection的文件:

class DBConnection 
    { 
     #region Database connection method 
     public SqlConnection Connect() 
     { 
      SqlConnection conn = new SqlConnection(); 
      conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ToString(); 

      try 
      { 
       conn.Open(); 
      } 
      catch 
      { 
      } 
      return conn; 
     } 
     #endregion 
    } 

這是我的登錄表單:

SqlCommand cmd; 
     DataSet ds = new DataSet(); 
     DBConnection db = new DBConnection(); 

     private void btnLogin_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       if (txtUserName.Text == "" || txtPassword.Text == "") 
       { 
        lblError.Visible = true; 
        lblError.Text = "*Enter UserName and Password"; 
        //MessageBox.Show(" Enter UserName and Password ."); 
        return; 
       } 
       else 
       { 
        string sql = "SELECT * FROM login_info WHERE userName = '" + txtUserName.Text + "' and password = '" + txtPassword.Text + "'"; 
        cmd = new SqlCommand(sql, db.Connect()); 
        SqlDataAdapter da = new SqlDataAdapter(cmd); 
        da.Fill(ds); 
        int i = ds.Tables[0].Rows.Count; 
        if (i == 1) 
        { 
         this.Hide(); 
         Home hm = new Home(); 
         hm.Show(); 
         ds.Clear(); 

        } 
        else 
        { 
         lblError.Text = "*Not Registered User or Invalid Name/Password"; 
         //MessageBox.Show("Not Registered User or Invalid Name/Password"); 
         txtPassword.Text = ""; 
        } 
       } 


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


     } 

但是當我的項目運行時,出現這個錯誤: 「對象引用未設置爲對象的實例。」 請給我一個解決方案。我利用一切適當的參考資料

+1

您能夠讀取連接字符串在調試時? – Sajeetharan

+1

你的錯誤是否發生在'conn.ConnectionString = ConfigurationManager.ConnectionStrings [「MegaPixelBizConn」]。行上ToString();'? – mason

+0

是的,錯誤發生在線'conn.ConnectionString = ConfigurationManager.ConnectionStrings [「MegaPixelBizConn」]。ToString();' –

回答

0

嘗試

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString); 

它應該工作

+0

提示:如果在配置文件中找不到請求的值,那麼將'ConfigurationManager'方法用於檢索應用程序設置和連接字符串與引發異常的代碼可能會非常有用。與追蹤另一個'NullReferenceException'相比,在配置中找不到「連接字符串」SecretDB「的異常是一個實時保護程序。 – HABO

3

立足我的答案上this solution,嘗試:

conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ConnectionString; 

確保您有System.Configuration參考爲好。

還記得關閉你的connection

編輯

根據您的新的編輯,嘗試一下本作你的代碼(注意:我很遺憾不能測試,如果這個工程,由於我的電腦被打破)。

private void btnLogin_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      if (txtUserName.Text == "" || txtPassword.Text == "") 
      { 
       lblError.Visible = true; 
       lblError.Text = "*Enter UserName and Password"; 
       //MessageBox.Show(" Enter UserName and Password ."); 
       return; 
      } 
      else 
      { 

       using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ConnectionString)) 
       { 

        con.Open(); 

        using (SqlCommand cmd = new SqlCommand("SELECT * FROM login_info WHERE userName = @Username AND password = @Password", con)) 
        { 
         // If these two lines don't work, replace "Username" and "Password" with "@Username"/"@Password" 
         cmd.Parameters.Add(new SqlParameter("Username", txtUserName.Text); 
         cmd.Parameters.Add(new SqlParameter("Password", txtPassword.Text); 
         SqlDataReader r = cmd.ExecuteReader(); 
         if(r.HasRows()) 
         { 
          // this assumes that there is only one user/password and no two users with same UID and PWORD 
          this.Hide(); 
          Home hm = new Home(); 
          hm.Show(); 
         } 

         else 
         { 
          lblError.Text = "*Not Registered User or Invalid Name/Password"; 
          //MessageBox.Show("Not Registered User or Invalid Name/Password"); 
          txtPassword.Text = ""; 
         } 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 


    } 

這也有助於防止出現SqlInjections

+0

你應該建議它重複......並且它不太可能幫助OP假設'ConfigurationManager.ConnectionStrings [「MegaPixelBizConn」]爲空... –

+0

你是對的評論,它是重複的。鑑於提供的Xml,我們可以說這是null嗎? – Hayden

+0

我有System.Configuration參考。以及我使用此代碼'conn.ConnectionString = ConfigurationManager.ConnectionStrings [「MegaPixelBizConn」]。ConnectionString;'但錯誤即將到來。 –

相關問題