2013-03-21 35 views
11

我正在學習通過單擊按鈕從文本框寫入數據庫。我在我的web.config文件中指定了連接字符串給我的NorthWind數據庫。但是,我無法訪問後面的代碼中的連接字符串。從web.config文件獲取sql連接字符串

這是我試過的。

protected void buttontb_click(object sender, EventArgs e) 
{ 
    System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham"); 
    System.Configuration.ConnectionStringSettings constring; 
    constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"]; 
    SqlConnection sql = new SqlConnection(constring); 

    sql.Open(); 
    SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql); 
    comm.ExecuteNonQuery(); 
    sql.Close(); 
} 

我得到

SqlConnection sql = new SqlConnection(constring); 

一個提示錯誤的

System.data.SqlClient.Sqlconnection.Sqlconnection(字符串)有一些無效的參數。

我想加載從web.config在連接字符串中constring

+2

這是不相關的問題,而是從文本框原因SQL注入寫入DB。 – Popeye 2013-03-21 06:30:38

+0

@Popeye是嗎?你有什麼建議?將用戶輸入值存儲在數據庫中的哪種方法更好? – 2013-03-21 06:34:01

+0

只要搜索谷歌,你也可以參考這個http://www.mikesdotnetting.com/Article/113/Preventing-SQL-Injection-in-ASP.NET – Popeye 2013-03-21 06:36:59

回答

8

這是因爲ConnectionStrings收集ConnectionStringSettings對象的集合,但SqlConnection構造函數需要一個string參數。所以你不能僅僅通過constring

試試這個。

SqlConnection sql = new SqlConnection(constring.ConnectionString); 
+0

工作。謝謝。 – 2013-03-21 06:34:30

4

試試這個

readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString()); 
0

我會建議你創建一個函數,而不是直接訪問web.config文件如下

public static string GetConfigurationValue(string pstrKey) 
    { 
     var configurationValue = ConfigurationManager.AppSettings[pstrKey]; 
     if (!string.IsNullOrWhiteSpace(configurationValue)) 
      return configurationValue; 

     throw (new ApplicationException(
      "Configuration Tag is missing web.config. It should contain <add key=\"" + pstrKey + "\" value=\"?\"/>")); 

    } 

而且在你的應用程序

使用此功能
9

您可以簡單地給 web.config文件,並做到這一點:

的web.config:

<add name="ConnectionStringName" connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/> 

代碼背後:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString()); 
相關問題