簡體   English   中英

為什么在保存數據庫條目時會收到​​“未處理的異常”?

[英]Why am I getting an "unhandled exception" when saving a database entry?

我目前正在開發一個數據庫,用於跟蹤停在停車場的車輛。 但是,我在將新記錄保存到數據庫表時遇到了一些問題。 現在我對編程還很陌生,所以我無法理解我收到的錯誤。 我嘗試查找並發現了類似的情況,但並不完全相同。 我已經在 C# 中創建了應用程序,我的數據庫是一個訪問 .mdb 文件。

我得到的當前錯誤如下:

“System.Data.dll 中發生類型為“System.InvalidOperationException”的未處理異常

附加信息:不允許更改“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

如果有人想知道調用堆棧中的 Unknown 位於 Language 列中。

在代碼示例中,您可能會注意到第 57 行,com.ExecuteNonQuery(); ,被注釋掉了。 這樣做的原因是我遇到了語法錯誤。

對此的任何幫助將不勝感激。 如果我需要提供更多信息,請告訴我。

血行者

還有一個錯字:

這個:

com.Parameters.AddWithValue("@[標簽#", 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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM