SqlDataReader引发的异常

我在做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: 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值