【发布时间】:2012-03-28 19:47:48
【问题描述】:
我正在开发一个打开数据库连接并从中检索数据以显示给用户的应用程序。在我可以看到的代码中,一切看起来都很好,但是由于下面的方法中引发了异常,所以出了点问题。我在“conn.Open();”处放置了一个断点在那里抛出异常。
我不知道如何找出实际错误是什么以及如何解决它,希望在这里得到一些帮助。如果有帮助,可以在 here 找到异常的堆栈跟踪。
异常是:System.ApplicationException: 应用程序出错
提前致谢!
抛出异常的方法:
public List<Movie> GetMovies() {
var movieTitles = new List<Movie>(100);
using (var conn = CreateConnection()) {
try {
var cmd = new SqlCommand("dbo.usp_GetMovies", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
using (var reader = cmd.ExecuteReader()) {
var movieIDIndex = reader.GetOrdinal("MovieID");
var nameIndex = reader.GetOrdinal("Name");
var yearIndex = reader.GetOrdinal("Year");
var lengthIndex = reader.GetOrdinal("Length");
var summaryIndex = reader.GetOrdinal("Summary");
while (reader.Read()) {
movieTitles.Add(new Movie {
MovieID = reader.GetInt32(movieIDIndex),
Name = reader.GetString(nameIndex),
Year = reader.GetInt32(yearIndex),
Length = reader.GetInt32(lengthIndex),
Summary = reader.GetString(summaryIndex),
});
}
}
}
catch {
throw new ApplicationException("An error occured!");
}
}
movieTitles.TrimExcess();
return movieTitles;
}
这是包含上述方法的类的基类:
public abstract class DALBase {
private static string _connectionString;
static DALBase() {
_connectionString = WebConfigurationManager.ConnectionStrings["NameOfTheDatabase_ConnectionString"].ConnectionString;
}
protected SqlConnection CreateConnection() {
return new SqlConnection(_connectionString);
}
}
来自 web.config:
<connectionStrings>
<add name="NameOfTheDatabase_ConnectionString" connectionString="Data Source=xxx.xx.xxx.x;Initial Catalog=The_Catalog;User ID=xxxxxx;Password=xxxxxx" providerName="System.Data.SqlClient"/>
</connectionStrings>
【问题讨论】:
-
如果在打开连接时抛出异常,我的猜测是连接字符串有问题。通过打开 VS2010 连接对话框并使用该对话框构建字符串来确认连接字符串有效。如果您可以连接,则排除此问题 - 如果您不能,则连接字符串不是有效的,您有答案。
标签: c# asp.net sql exception sqlconnection