从数据库读取时,WebException未处理

时间:2012-06-26 15:51:57

标签: c# sql wpf exception

我在做什么很简单。我只需要连接到SQL数据库并从表中读取信息。我确信我错过了一些愚蠢的事情。我正在使用C#,SQL Sever和WPF。显示的连接字符串是数据源构建器提供的连接字符串,因此我认为它是正确的。我用它测试了连接并且它成功了。我附上了一些代码和图片,以帮助您解决我的问题。

代码:

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    con = new System.Data.SqlClient.SqlConnection();

    con.ConnectionString = "Data Source=USSW7DEVWS16\\DEVELOPER;Initial Catalog=acrGIS;Integrated Security=True";

    con.Open();
    using (SqlCommand command = new SqlCommand("SELECT * FROM dbo.acrObjects", con))
    {
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            string Object = reader.GetString(0);
            string Comment = reader.GetString(1);
            string OStreet = reader.GetString(2);
            string OCity = reader.GetString(3);
            string OState = reader.GetString(4);
            string OZip = reader.GetString(5);
            string OSpec = reader.GetString(6);

            arcObjects.Add(new acrObject() { Object_Num = Object, Comments = Comment, Street = OStreet, City = OCity, State = OState, Zip = OZip, Spec = OSpec });
        }
        foreach (acrObject objects in arcObjects)
        {
           MessageBox.Show(objects.ToString());
        }
    } 

这是我的班级以及我的列表和连接定义:

class acrObject
{
    public string Object_Num {get; set;}
    public string Comments{get; set;}
    public string Street {get; set;}
    public string City {get; set;}
    public string State{get; set;}
    public string Zip {get; set;}
    public string Spec {get; set;}
    public override string  ToString()
    {
              return string.Format("Object Number: {0}, Comments: {1}, Street: {2}, City: {3}, State: {4}, Zip: {5}, Spec: {6}", Object_Num, Comments, Street, City, State, Zip, Spec);
    }
}



System.Data.SqlClient.SqlConnection con;

        List<acrObject> arcObjects = new List<acrObject>();

异常图片:

enter image description here

它发生在这一行:

while (reader.Read())

更奇怪的是,有时错误不会被抛出并且它会跳过所有代码。所以它永远不会试图显示我发现的消息框是如此奇怪。谢谢您的帮助。如果您有任何其他问题或希望我发布更多我的代码,请告诉我,我将很乐意。

显示断点和调用堆栈:

enter image description here

以下是执行try / catch时抛出的异常:

enter image description here

1 个答案:

答案 0 :(得分:0)

确保您的应用有权访问dbo架构,并确保在arcObjects架构中创建了dbo

  1. 您可以通过执行SELECT SCHEMA_NAME()来检查登录的默认架构。或者,您可以在Security&gt;下找到数据库中的登录信息。用户并查看其属性。您可以检查默认架构以及它拥有的任何其他架构。例如,如果您不希望该身份具有完全权限,则可以将用户添加到db_owner,或者可能db_datareader / db_datawriter
  2. 检查表所属的架构:
  3. 在新的查询窗口中执行以下SQL:

    select t.name as table_name, s.name as schema_name from sys.tables as t 
        inner join sys.schemas as s on t.schema_id = s.schema_id
    where object_id = OBJECT_ID(N'arcObjects')
    

    如果该表属于dbo,则应在dbo列下显示schema_name。如果没有,请将表格移至dbo

     ALTER SCHEMA dbo 
     TRANSFER [schema listed in schema_name column].arcObjects
    

    或者,您可以浏览对象资源管理器中的表。这些表格将以[架构]。[表格名称]格式列出。