2013-03-21 56 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());