ASP.NET如何使用web.config连接本地SQL Server数据库?

7

为什么System.Data.SqlClient.SqlConnection类会抛出“参数不正确”的异常?

我正在尝试学习如何使用本地SQL数据库和ASP.NET MVC项目设置数据库连接,使用的是.NET Framework 4.5。

以下是导致此问题的步骤:

  1. Created a new SQL Server database in my project App_Data folder, called TestSQLdb.mdf.

  2. Created a connection string in web.config:

    <add name="SQLTestConnection1" 
         connectionString="Data Source=(LocalDB);initial catalog=TestSQLdb;Integrated Security=true" />  
    
  3. Access the connection string through

    string cn_str = ConfigurationManager.ConnectionStrings["SQLTestConnection1"].ConnectionString;
    

    (See this SO thread for more info on this).

  4. Created a new connection:

    SqlConnection conn = new SqlConnection(cn_str);
    
  5. Attempt to open the connection:

    try
    {
         conn.Open();
    

    At this point, an exception is thrown.

我试图设置这个以便它简单易学。但我错过了什么?


你是不是真的在你的new SqlConnection中调用了一个叫做cn_str()的方法,还是只是打错了字? - Pilgerstorfer Franz
@PilgerstorferFranz:我的代码中cn_str()方法是正确的,但例如在这里它应该只是cn_str。感谢您指出这一点。我会编辑我的问题,因为@NightOwl888在他下面的答案中也指出了这一点。 - Aaron Thomas
2个回答

9
当您使用本地数据库时,必须在连接字符串中指定AttachDbFileName属性。该属性应指向您的TestSQLdb.mdf文件。Initial catalog是您的mdf文件中数据库的名称。
请参阅MSDN以获取此示例。
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;InitialCatalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True" />

好的,搞定了。感谢提供有用的链接,加一分。 - Aaron Thomas

0

您没有将变量传递给new SqlConnection,而是尝试调用名为cn_str的函数。

要使其正常工作,您需要从名称中删除括号。

SqlConnection conn = new SqlConnection(cn_str);

嗯,我的错,我没有指出我实际上是使用一个函数来获取cn_str。谢谢你指出这一点,但我认为这并不是问题所在。如果需要的话,我会编辑我的问题。 - Aaron Thomas
如果这是问题的原因,错误信息将会不同,并且异常会在不同的时间发生。 - mason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接