从web获取sql连接字符串.配置文件
本文关键字:字符串 配置文件 连接 sql web 获取 | 更新日期: 2023-09-27 18:04:55
我正在学习从一个文本框中写入一个数据库,点击一个按钮。我已经在我的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)有一些无效的参数
我想从constring
中的web.config
加载连接字符串
您可以简单地给web.config
文件中的ConnectionString
一个Name
,并这样做:
网络。配置:
<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);
try this
readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());
我建议您创建一个函数,而不是直接访问web。配置文件如下
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='"?'"/>"));
}
在你的应用程序中使用这个函数