2016-08-01 47 views
0

我想從VS2013中的網頁訪問數據庫。它給我的錯誤從網頁訪問數據庫時出錯

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"

我的代碼:

@{ 
    var db = Database.Open("Rohit"); 
    var selectQueryString = "SELECT * FROM Sample"; 
} 
<html> 
<body> 
<h1>Small Bakery Products</h1> 
<table> 
    <tr> 
     <th>Id</th> 
     <th>Name</th> 
    </tr> 
    @foreach (var row in db.Query(selectQueryString)) 
    { 
     <tr> 
      <td>@row.Id</td> 
      <td>@row.Name</td> 

     </tr> 
    } 
</table> 

這是給錯誤的@foreach線。

回答

0

Database.Open(name)方法將連接到一個數據庫中的兩個步驟:

首先,它會搜索應用程序的App_Data文件夾的名稱參數匹配不帶文件擴展名的數據庫。

如果找不到文件,它會在應用程序的Web.config文件中查找「connection string」。

(連接字符串包含有關如何連接到一個數據庫中的信息,可以包含一個文件路徑或SQL數據庫的名稱,擁有完全用戶名和密碼)

這兩步搜索品牌可以使用本地數據庫測試應用程序,並使用連接字符串在Web主機上運行應用程序。

現在考慮這些步驟並嘗試連接到您的數據庫。

+0

錯誤在行 - @foreach(var.db.Query(selectQueryString)中的行)。因此,我認爲連接數據庫沒有問題 – user2095748

+0

請確保您在AppCode文件夾中具有'.mdf'文件並且'Web.config'中具有'ConnectionString' – mmushtaq

+0

我可以在App_Data文件夾中找到我的數據庫。但是web.config中不存在相對連接字符串。 – user2095748

0

錯誤消息說明了所有 - 數據庫無法打開 - 可能由於錯誤的連接字符串或網絡/數據庫配置而發生。要解決問題,嘗試在web.config文件

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <connectionStrings> 
    <add 
    name="Rohit" 
    connectionString= "server=myServer;database=myDatabase;uid=username;pwd=password" 
    providerName="System.Data.SqlClient" /> 

    </connectionStrings> 
</configuration> 

添加一個完整的連接字符串,並驗證是否可以使用SQL Server Management Studio中(或其他喜歡的SQL工具)時,打開您的數據庫。

+0

在Web.config中添加了連接字符串。 現在得到這個錯誤「類型爲'System.Data.SqlServerCe的異常。 SqlCeException'發生在System.Data.SqlServerCe.dll中,但未在用戶代碼中處理「 – user2095748