SqlDataReader引发的异常

本文介绍了一个使用SqlDataReader类从Teacher表读取数据的例子,并遇到了连接字符串配置错误导致的异常。通过分析异常堆栈,指出了服务器不支持用户实例的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在做SqlDataReader的练习时,遇到课本上一个例子,结果运行出行一些异常,但是我又不明白它为什么会出现这样的异常,也不知道要怎么解决.

 

 

功能:使用SqlDataReader 类顺序读出StudentMis数据库Teacher表工号和教师名字逐一显示。

 

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;

namespace SqlDataReader类
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        SqlConnection conn; 
        SqlCommand da; 
        SqlDataReader dr;
        public Window1()
        {
            InitializeComponent();
            string s = "DATABASE = E:\\DB\\StudentMis.mdf;SERVER=PC-20110304BTZV\\PC_SERVER;Integrated Security =True;";
            

            conn = new SqlConnection(s);
            s = "SELECT * FROM Teacher";
            da = new SqlCommand(s, conn);
            conn.Open();
            dr = da.ExecuteReader();            
            button1_Click(null, null);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
              
            if (dr.Read())
            {
                textBlock2.Text = dr.GetInt32(0).ToString();
                textBlock4.Text = (dr.GetSqlString(1)).ToString();
            }
            else
            {
                MessageBox.Show("最后一个记录");
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            conn.Close();
        }
    }
}

 

 

 

 

 

 

 
 
 
 
 
 
 
异常信息为:

未处理 System.Windows.Markup.XamlParseException
Message="无法创建在程序集“SqlDataReader类, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中定义的“Window1”的实例。 调用的目标发生了异常。 标记文件中“Window1.xaml”行1位置9处的错误。"
Source="PresentationFramework"
LineNumber=1
LinePosition=9
StackTrace:
在 System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)
在 System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException)
在 System.Windows.Markup.BamlRecordReader.ThrowExceptionWithLine(String message, Exception innerException)
在 System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail)
在 System.Windows.Markup.BamlRecordReader.GetElementAndFlags(BamlElementStartRecord bamlElementStartRecord, Object& element, ReaderFlags& flags, Type& delayCreatedType, Int16& delayCreatedTypeId)
在 System.Windows.Markup.BamlRecordReader.BaseReadElementStartRecord(BamlElementStartRecord bamlElementRecord)
在 System.Windows.Markup.BamlRecordReader.ReadElementStartRecord(BamlElementStartRecord bamlElementRecord)
在 System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
在 System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord)
在 System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment()
在 System.Windows.Markup.TreeBuilder.Parse()
在 System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
在 System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
在 System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
在 System.Windows.Application.DoStartup()
在 System.Windows.Application.<.ctor>b__0(Object unused)
在 System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
在 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
在 System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
在 System.Windows.Threading.DispatcherOperation.InvokeImpl()
在 System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
在 System.Threading.ExecutionContext.runTryCode(Object userData)
在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Windows.Threading.DispatcherOperation.Invoke()
在 System.Windows.Threading.Dispatcher.ProcessQueue()
在 System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
在 MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
在 MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
在 System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
在 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
在 System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
在 System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
在 System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
在 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
在 MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
在 System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
在 System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
在 System.Windows.Threading.Dispatcher.Run()
在 System.Windows.Application.RunDispatcher(Object ignore)
在 System.Windows.Application.RunInternal(Window window)
在 System.Windows.Application.Run(Window window)
在 System.Windows.Application.Run()
在 SqlDataReader类.App.Main() 位置 C:\Users\Administrator\Desktop\e9_3\SqlDataReader类\obj\Debug\App.g.cs:行号 0
在 System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Reflection.TargetInvocationException
Message="调用的目标发生了异常。"
Source="mscorlib"
StackTrace:
在 System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
在 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
在 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
在 System.Activator.CreateInstance(Type type, Boolean nonPublic)
在 System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail)
InnerException: System.Data.SqlClient.SqlException
Message="在连接字符串中请求了用户实例,但是指定的服务器不支持此选项。\r\n已将数据库上下文改为 'master'。\r\n已将语言设置改为 简体中文。"
Source=".Net SqlClient Data Provider"
ErrorCode=-2146232060
Class=20
LineNumber=0
Number=0
Procedure=""
Server="PC-20110304BTZV\\PC_SERVER"
State=0
StackTrace:
在 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
在 System.Data.SqlClient.TdsParser.ProcessLoginAck(TdsParserStateObject stateObj)
在 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
在 System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
在 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
在 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
在 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
在 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
在 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
在 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
在 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
在 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
在 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
在 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
在 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
在 System.Data.SqlClient.SqlConnection.Open()
在 SqlDataReader类.Window1..ctor() 位置 C:\Users\Administrator\Desktop\e9_3\SqlDataReader类\Window1.xaml.cs:行号 35
InnerException: 


### C# 异常处理的最佳实践 在 C# 编程中,异常处理是一种用于管理错误情况的强大工具。以下是关于如何高效使用 `try`、`catch` 和 `throw` 的最佳实践以及一些具体的示例。 #### 使用 try-catch 块捕获异常执行可能引发异常的操作时,应将其包裹在一个 `try` 块中,并提供相应的 `catch` 块来处理这些异常。这有助于防止应用程序崩溃并允许程序继续运行或采取其他措施。 ```csharp try { int result = 10 / 0; } catch (DivideByZeroException ex) { Console.WriteLine($"Error: {ex.Message}"); // 显示错误消息给用户 } finally { Console.WriteLine("This block will always execute."); // 清理资源或其他操作 } ``` 上述代码展示了如何捕捉除零错误的情况[^1]。无论是否发生异常,`finally` 块都会被执行,通常用来释放资源或者关闭文件流等。 #### 自定义异常类 创建自定义异常可以更精确地描述特定业务逻辑中的失败原因。这样可以使调用者更容易理解发生了什么问题,并能做出适当反应。 ```csharp public class InvalidUserInputException : Exception { public InvalidUserInputException(string message) : base(message) {} } // Usage Example: if (!IsValid(input)) { throw new InvalidUserInputException("The input provided is invalid."); } ``` 这里定义了一个新的异常类型 `InvalidUserInputException` 来表示输入验证失败的情形[^2]。 #### 避免空泛的 catch-all 子句 虽然可以用通用的方式捕获所有类型的异常 (`catch(Exception e)`), 这种做法并不推荐除非绝对必要。因为这样做可能会隐藏潜在的问题并且使得调试更加困难。相反应该针对预期可能出现的具体异常种类编写单独的处理器。 #### 不要忽略被捕获到的异常 即使有时候看起来好像不需要做任何事情就可以恢复状态,在大多数情况下仍然建议至少记录下发生的事件以便后续分析诊断目的。 #### 考虑性能影响 频繁抛掷和接收大量小型对象实例会消耗内存并对GC造成压力;因此应当谨慎对待那些仅为了控制流程而设计的小型内部方法内的简单分支判断场景下的应用案例[^3]. #### 结合日志功能 每当遇到未预料之外状况之时都应该考虑加入足够的上下文信息进入追踪系统当中去帮助开发者快速定位根源所在之处. --- ### 示例教程:构建健壮的应用程序结构 假设我们要开发一款简单的图书管理系统,其中涉及到了数据库交互部分,则可以通过如下方式实现: 1. **分离关注点**: 将 UI 层与数据访问层分开. ```csharp /// <summary> /// Represents an entity that holds book information. /// </summary> public class Book { public string Title { get; set; } public string Author { get; set; } } /// <summary> /// Handles all database related operations regarding books. /// </summary> internal static class BooksRepository { private const string ConnectionString = "YourConnectionString"; public static List<Book> GetAllBooks() { using(SqlConnection conn = new SqlConnection(ConnectionString)) { SqlCommand cmd = new SqlCommand("SELECT * FROM Books", conn); try { conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); var list = new List<Book>(); while(reader.Read()) { list.Add(new Book(){ Title = reader["Title"].ToString(), Author=reader["Author"].ToString() }); } return list; } catch (SqlException sqlEx){ Log.Error(sqlEx); throw new DataAccessException("Failed to retrieve books.",sqlEx)[^4]; } } } } ``` 此例子说明了怎样合理运用分层架构模式的同时也体现了良好的异常传播策略——即从底层向上逐级传递直至最上层决定最终处置方案为止的过程。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值