为什么我得到一个“未处理的异常”?保存数据库条目时

本文关键字:异常 保存 数据库 未处理 一个 为什么 | 更新日期: 2023-09-27 18:12:59

我目前正在开发一个数据库,用于跟踪停放在停车场的车辆。然而,我遇到了一些问题,将新记录保存到数据库表。现在我仍然相当新的程序,所以我有困难理解我收到的错误。我试着查了一下,发现了类似的情况,但不完全相同。我已经在c#中创建了应用程序,我的数据库是一个访问.mdb文件。

我得到的当前错误如下:

"类型为'System '的未处理异常。InvalidOperationException'在System.Data.dll中发生

附加信息:不允许更改'ConnectionString'属性。连接的当前状态为打开"

我想指出,这只发生在我点击保存,有值在文本框中。如果我点击保存而不输入任何东西,它会说"客人信息保存成功"。

我不知道发生了什么事,所以我希望这里有人能帮助我。到目前为止,我已经为我的应用程序提供了调用堆栈的代码。

下面是我的应用程序的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.OleDb;
using System.Data;
using System.ComponentModel;

namespace ParkingDatabase
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    OleDbConnection DBConnect = new OleDbConnection();
    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        DBConnect.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:'Users'bkoso'Documents'Visual Studio 2015'Projects'ParkingDatabase'ParkingDatabase'ParkingData.mdb";
        DBConnect.Open();
        OleDbCommand com = new OleDbCommand("INSERT INTO Guest Info([Guest FName], [Guest LName], [Room #], Departure, Return, [Vehicle Colour], [Vehicle Make], [Plate #], [Contact FName], [Contact LName], [Contact #], [Contact Email], [Tag #]) Values(@[Guest FName], @[Guest LName], @[Room #], @Departure, @Return, @[Vehicle Colour], @[Vehicle Make], @[Plate #], @[Contact FName], @[Contact LName], @[Contact #], @[Contact Email], @[Tag #])", DBConnect);
            com.Parameters.AddWithValue("@[Guest FName]", txtBxGstFName.Text);
            com.Parameters.AddWithValue("@[Guest LName]", txtBxGstLName.Text);
            com.Parameters.AddWithValue("@[Room #]", txtBxRm.Text);
            com.Parameters.AddWithValue("@Departure", txtBxDDate.Text);
            com.Parameters.AddWithValue("@[Return]", txtBxRDate.Text);
            com.Parameters.AddWithValue("@[Vehicle Colour]", txtBxVColour.Text);
            com.Parameters.AddWithValue("@[Vehicle Make]", txtBxVMake.Text);
            com.Parameters.AddWithValue("@[Plate #]", txtBxPlate.Text);
            com.Parameters.AddWithValue("@[Contact FName]", txtBxContactFName.Text);
            com.Parameters.AddWithValue("@[Contact LName]", txtBxContactLName.Text);
            com.Parameters.AddWithValue("@[Contact #]", txtBxPhone.Text);
            com.Parameters.AddWithValue("@[Contact Email]", txtBxEmail.Text);
            com.Parameters.AddWithValue("@[Tag #", txtBxTag.Text);
        if (DBConnect.State == ConnectionState.Open)
        {
            try
            {
                //com.ExecuteNonQuery();
                MessageBox.Show("Guest Information Saved Successfully");
                txtBxGstFName.Text = "";
                txtBxGstLName.Text = "";
                txtBxRm.Text = "";
                txtBxDDate.Text = "";
                txtBxRDate.Text = "";
                txtBxVColour.Text = "";
                txtBxVMake.Text = "";
                txtBxPlate.Text = "";
                txtBxContactFName.Text = "";
                txtBxContactLName.Text = "";
                txtBxPhone.Text = "";
                txtBxEmail.Text = "";
                txtBxTag.Text = "";
            }
            catch (Exception notSaved)
            {
                if (DBConnect != null && DBConnect.State != ConnectionState.Closed)
                {
                    DBConnect.Close();
                }
                MessageBox.Show("Error Saving Data 'n" + notSaved.ToString());
                DBConnect.Close();
            }
        }
        else
        {
            MessageBox.Show("Connection Failed");
        }
    }
    private void btnClear_Click(object sender, RoutedEventArgs e)
    {
    }
    private void btnView_Click(object sender, RoutedEventArgs e)
    {
    }
    private void btnSame_Click(object sender, RoutedEventArgs e)
    {
    }
    private void txtBoxGuestFirstName_TextChanged(object sender, TextChangedEventArgs e)
    {
    }

}
}

下面是调用栈:

>   ParkingDatabase.exe!ParkingDatabase.MainWindow.btnSave_Click(object sender, System.Windows.RoutedEventArgs e) Line 36   C#
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs e)  Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick()   Unknown
PresentationFramework.dll!System.Windows.Controls.Button.OnClick()  Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)    Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseLeftButtonUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)  Unknown
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent)  Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)    Unknown
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args)    Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs args, bool trusted) Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input)  Unknown
PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport)   Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel)   Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)   Unknown
PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)    Unknown
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)  Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs)   Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam)  Unknown
[Native to Managed Transition]  
[Managed to Native Transition]  
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame)   Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame)   Unknown
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore)   Unknown
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window)  Unknown
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window)  Unknown
PresentationFramework.dll!System.Windows.Application.Run()  Unknown
ParkingDatabase.exe!ParkingDatabase.App.Main()  C#
[Native to Managed Transition]  
[Managed to Native Transition]  
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) Unknown
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()   Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state)    Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart()    Unknown

如果有人想知道调用堆栈中的未知是在语言列。

在代码示例中,您可能注意到第57行,com.ExecuteNonQuery();,被注释掉。这样做的原因是我得到了一个语法错误。 如果有任何帮助,我将不胜感激。如果我需要提供更多的信息,请告诉我。

Bloodstalker

为什么我得到一个“未处理的异常”?保存数据库条目时

还有一个错别字:

:

com.Parameters。AddWithValue("@[Tag #", txtBxTag.Text);

应:

com.Parameters。AddWithValue("@[标签#]",txtBxTag.Text);

using语句为您关闭连接。查看MSDN的OleDbConnection案例(跳转到文章末尾的"示例"部分)。

你的代码应该是这样的:
private void btnSave_Click(object sender, RoutedEventArgs e)
{
    using (OleDbConnection DBConnect = new OleDbConnection())
    {
        DBConnect.ConnectionString = @"Provider=Mi...";
        DBConnect.Open();
        OleDbCommand com = new OleDbCommand("INSERT INTO ...", DBConnect);
        // Parameters goes here
        if (DBConnect.State == ConnectionState.Open)
        {
            com.ExecuteNonQuery();
        }
        //...
        // No need to close connection
    }
}