![](/img/trans.png)
[英]Create DataTable from SQL Connection String in Web.config file
[英]Getting sql connection string from web.config file
我正在學習通過單擊按鈕從文本框寫入數據庫。 我已經在web.config
文件中指定了我的NorthWind數據庫的連接字符串。 但是,我無法訪問后面的代碼中的連接字符串。
這就是我嘗試過的。
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(string)有一些無效的參數。
我想加載從連接字符串web.config
中constring
您只需在web.config
文件中為您的ConnectionString
指定一個Name
,然后執行以下操作:
web.config中:
<add name="ConnectionStringName" connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>
代碼背后:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());
這是因為ConnectionStrings
集合是ConnectionStringSettings
對象的集合,但SqlConnection
構造函數需要一個string
參數。 所以你不能只是通過在constring
本身。
試試這個。
SqlConnection sql = new SqlConnection(constring.ConnectionString);
嘗試這個
readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());
我建議你創建一個函數而不是直接訪問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=\"?\"/>"));
}
並在您的應用程序中使用此功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.